Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 788da3a

Browse files
antmarakisnorvig
authored andcommitted
Update learning.ipynb (aimacode#541)
1 parent b14e21a commit 788da3a

File tree

1 file changed

+130
-117
lines changed

1 file changed

+130
-117
lines changed

learning.ipynb

Lines changed: 130 additions & 117 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
},
1212
{
1313
"cell_type": "code",
14-
"execution_count": 2,
14+
"execution_count": 1,
1515
"metadata": {
1616
"collapsed": true
1717
},
@@ -33,6 +33,7 @@
3333
"* k-Nearest Neighbours\n",
3434
"* Naive Bayes Learner\n",
3535
"* Perceptron\n",
36+
"* Neural Network\n",
3637
"* MNIST Handwritten Digits\n",
3738
" * Loading and Visualising\n",
3839
" * Testing\n",
@@ -913,121 +914,6 @@
913914
"The output of the above code is \"setosa\", which means the flower with the above measurements is of the \"setosa\" species."
914915
]
915916
},
916-
{
917-
"cell_type": "markdown",
918-
"metadata": {},
919-
"source": [
920-
"## Multilayer Perceptron Classifier\n",
921-
"\n",
922-
"### Overview\n",
923-
"\n",
924-
"Although the Perceptron may seem like a good way to make classifications, it is a linear classifier. A Perceptron can be used to represent both AND and OR boolean functions, but not the XOR one, which is a nonlinear function. In order to solve that, the MultiLayer Perceptron (MLP) or Neural Network can be used.\n",
925-
"\n",
926-
"Different from the Perceptron, the MultiLayer Perceptron is a nonlinear classifier, meaning that it can represent more robust functions. It achieves that by combining the results of linear functions on each layer of the network.\n",
927-
"Similar to the Perceptron, this network also has an input and output layer. However it can also have a number of hidden layers. These hidden layers are responsible for creating the nonlinearity of the MLP. A usual execution of an MLP is to feed the inputs into the first hidden layer. Every neuron on the hidden layer will behave exactly as one neuron on the Perceptron. After that, every value in the hidden layer is fed to the next hidden layer, until we feed the final layer, the output layer, which will be used to generate our classification.\n",
928-
"\n",
929-
"![multilayer_perceptron](images/multilayer_perceptron.png)"
930-
]
931-
},
932-
{
933-
"cell_type": "markdown",
934-
"metadata": {},
935-
"source": [
936-
"### Implementation\n",
937-
"\n",
938-
"First, we need to define a dataset and the number of neurons the hidden layer will have (we currently only support using one hidden layer). After that we will create our neural network in the `network` function. This function will make the necessary connections between the input layer, hidden layer and output layer. With the network ready, we will use the `BackPropagationLearner` to train the weights of our network for the examples provided in the dataset.\n",
939-
"\n",
940-
"The NeuralNetLearner returns the `predict` function, which will receive an example and feed forward it into our network to generate a prediction.\n",
941-
"\n",
942-
"NOTE: Like the PerceptronLearner, NeuralNetLearner is a binary classifier and will not work well for multi-class datasets."
943-
]
944-
},
945-
{
946-
"cell_type": "code",
947-
"execution_count": 3,
948-
"metadata": {},
949-
"outputs": [],
950-
"source": [
951-
"%psource NeuralNetLearner"
952-
]
953-
},
954-
{
955-
"cell_type": "markdown",
956-
"metadata": {},
957-
"source": [
958-
"### Backpropagation\n",
959-
"In both Perceptron and MLP, we are talking about the Backpropagation algorithm. This algorithm is the one used to train the weights of our learners. Basically it achieves that by propagating the errors from our last layer into our first layer, this is why it is called Backpropagation. In order to use Backpropagation, we need a cost function. This function is responsible for indicating how good our neural network is for a given example. One common cost function is the Mean Squared Error (MSE). This cost function has the following format:\n",
960-
"\n",
961-
"$$MSE=\\frac{1}{2} \\sum_{i=1}^{n}(y - \\hat{y})^{2}$$\n",
962-
"\n",
963-
"Where `n` is the number of training examples, $\\hat{y}$ is our prediction and $y$ is the correct prediction for the example.\n",
964-
"\n",
965-
"Backpropagation basically combines the concept of partial derivatives and the chain rule to generate the gradient for each weight in the network based on the cost function\n",
966-
"\n",
967-
"For example, considering we are using a Neural Network with three layers, the sigmoid function as our activation function and the MSE cost function, we want to find the gradient for the a given weight $w_{j}$, we can compute it like this:\n",
968-
"\n",
969-
"$$\\frac{\\partial MSE(\\hat{y}, y)}{\\partial w_{j}} = \\frac{\\partial MSE(\\hat{y}, y)}{\\partial \\hat{y}}\\times\\frac{\\partial\\hat{y}(in_{j})}{\\partial in_{j}}\\times\\frac{\\partial in_{j}}{\\partial w_{j}}$$\n",
970-
"\n",
971-
"Solving this equation, we have:\n",
972-
"\n",
973-
"$$\\frac{\\partial MSE(\\hat{y}, y)}{\\partial w_{j}} = (\\hat{y} - y)\\times{\\hat{y}}'(in_{j})\\times a_{j}$$\n",
974-
"\n",
975-
"Remember that $\\hat{y}$ is the activation function applied to a neuron in our hidden layer, therefore $$\\hat{y} = sigmoid(\\sum_{i=1}^{num\\_neurons}w_{i}\\times a_{i})$$\n",
976-
"\n",
977-
"Also $a$ is the input generated by feeding the input layer variables into the hidden layer.\n",
978-
"\n",
979-
"We can use the same technique for the weights in the input layer as well. After we have the gradients for both weights, we use gradient descent to update the weights of the network."
980-
]
981-
},
982-
{
983-
"cell_type": "markdown",
984-
"metadata": {},
985-
"source": [
986-
"### Implementation\n",
987-
"\n",
988-
"First, we feed forward the examples in our neural network. After that, we calculate the gradient for each layer weights. Once that is complete, we update all the weights using gradient descent. After running these for a given number of epochs (number of time we will pass over all the training examples), the function returns the trained Neural Network."
989-
]
990-
},
991-
{
992-
"cell_type": "code",
993-
"execution_count": 4,
994-
"metadata": {
995-
"collapsed": true
996-
},
997-
"outputs": [],
998-
"source": [
999-
"%psource BackPropagationLearner"
1000-
]
1001-
},
1002-
{
1003-
"cell_type": "code",
1004-
"execution_count": 8,
1005-
"metadata": {},
1006-
"outputs": [
1007-
{
1008-
"name": "stdout",
1009-
"output_type": "stream",
1010-
"text": [
1011-
"0\n"
1012-
]
1013-
}
1014-
],
1015-
"source": [
1016-
"iris = DataSet(name=\"iris\")\n",
1017-
"iris.remove_examples(\"virginica\")\n",
1018-
"iris.classes_to_numbers()\n",
1019-
"\n",
1020-
"mlp = NeuralNetLearner(iris)\n",
1021-
"print(mlp([5,3,1,0.1]))"
1022-
]
1023-
},
1024-
{
1025-
"cell_type": "markdown",
1026-
"metadata": {},
1027-
"source": [
1028-
"The output is 0, which means the item is classified in the first class, *setosa*. As the perceptron learner, it has classified the example correctly."
1029-
]
1030-
},
1031917
{
1032918
"cell_type": "markdown",
1033919
"metadata": {},
@@ -1448,7 +1334,134 @@
14481334
"cell_type": "markdown",
14491335
"metadata": {},
14501336
"source": [
1451-
"The output is 0, which means the item is classified in the first class, \"Setosa\". This is indeed correct. Note that the Perceptron algorithm is not perfect and may produce false classifications."
1337+
"The correct output is 0, which means the item belongs in the first class, \"setosa\". Note that the Perceptron algorithm is not perfect and may produce false classifications."
1338+
]
1339+
},
1340+
{
1341+
"cell_type": "markdown",
1342+
"metadata": {},
1343+
"source": [
1344+
"## Neural Network\n",
1345+
"\n",
1346+
"### Overview\n",
1347+
"\n",
1348+
"Although the Perceptron may seem like a good way to make classifications, it is a linear classifier (which, roughly, means it can only draw straight lines to divide spaces) and therefore it can be stumped by more complex problems. We can extend Perceptron to solve this issue, by employing multiple layers of its functionality. The construct we are left with is called a Neural Network, or a Multi-Layer Perceptron, and it is a non-linear classifier. It achieves that by combining the results of linear functions on each layer of the network.\n",
1349+
"\n",
1350+
"Similar to the Perceptron, this network also has an input and output layer. However it can also have a number of hidden layers. These hidden layers are responsible for the non-linearity of the network. The layers are comprised of nodes. Each node in a layer (excluding the input one), holds some values, called *weights*, and takes as input the output values of the previous layer. The node then calculates the dot product of its inputs and its weights and then activates it with an *activation function* (sometimes a sigmoid). Its output is fed to the nodes of the next layer. Note that sometimes the output layer does not use an activation function, or uses a different one from the rest of the network. The process of passing the outputs down the layer is called *feed-forward*.\n",
1351+
"\n",
1352+
"After the input values are fed-forward into the network, the resulting output can be used for classification. The problem at hand now is how to train the network (ie. adjust the weights in the nodes). To accomplish that we utilize the *Backpropagation* algorithm. In short, it does the opposite of what we were doing up to now. Instead of feeding the input forward, it will feed the error backwards. So, after we make a classification, we check whether it is correct or not, and how far off we were. We then take this error and propagate it backwards in the network, adjusting the weights of the nodes accordingly. We will run the algorithm on the given input/dataset for a fixed amount of time, or until we are satisfied with the results. The number of times we will iterate over the dataset is called *epochs*. In a later section we take a detailed look at how this algorithm works.\n",
1353+
"\n",
1354+
"NOTE: Sometimes we add to the input of each layer another node, called *bias*. This is a constant value that will be fed to the next layer, usually set to 1. The bias generally helps us \"shift\" the computed function to the left or right."
1355+
]
1356+
},
1357+
{
1358+
"cell_type": "markdown",
1359+
"metadata": {},
1360+
"source": [
1361+
"![multilayer_perceptron](images/multilayer_perceptron.png)"
1362+
]
1363+
},
1364+
{
1365+
"cell_type": "markdown",
1366+
"metadata": {},
1367+
"source": [
1368+
"### Implementation\n",
1369+
"\n",
1370+
"The `NeuralNetLearner` function takes as input a dataset to train upon, the learning rate (in (0, 1]), the number of epochs and finally the size of the hidden layers. This last argument is a list, with each element corresponding to one hidden layer.\n",
1371+
"\n",
1372+
"After that we will create our neural network in the `network` function. This function will make the necessary connections between the input layer, hidden layer and output layer. With the network ready, we will use the `BackPropagationLearner` to train the weights of our network for the examples provided in the dataset.\n",
1373+
"\n",
1374+
"The NeuralNetLearner returns the `predict` function, which can receive an example and feed-forward it into our network to generate a prediction."
1375+
]
1376+
},
1377+
{
1378+
"cell_type": "code",
1379+
"execution_count": 3,
1380+
"metadata": {
1381+
"collapsed": true
1382+
},
1383+
"outputs": [],
1384+
"source": [
1385+
"%psource NeuralNetLearner"
1386+
]
1387+
},
1388+
{
1389+
"cell_type": "markdown",
1390+
"metadata": {},
1391+
"source": [
1392+
"### Backpropagation\n",
1393+
"\n",
1394+
"In both the Perceptron and the Neural Network, we are using the Backpropagation algorithm to train our weights. Basically it achieves that by propagating the errors from our last layer into our first layer, this is why it is called Backpropagation. In order to use Backpropagation, we need a cost function. This function is responsible for indicating how good our neural network is for a given example. One common cost function is the *Mean Squared Error* (MSE). This cost function has the following format:\n",
1395+
"\n",
1396+
"$$MSE=\\frac{1}{2} \\sum_{i=1}^{n}(y - \\hat{y})^{2}$$\n",
1397+
"\n",
1398+
"Where `n` is the number of training examples, $\\hat{y}$ is our prediction and $y$ is the correct prediction for the example.\n",
1399+
"\n",
1400+
"The algorithm combines the concept of partial derivatives and the chain rule to generate the gradient for each weight in the network based on the cost function.\n",
1401+
"\n",
1402+
"For example, if we are using a Neural Network with three layers, the sigmoid function as our activation function and the MSE cost function, we want to find the gradient for the a given weight $w_{j}$, we can compute it like this:\n",
1403+
"\n",
1404+
"$$\\frac{\\partial MSE(\\hat{y}, y)}{\\partial w_{j}} = \\frac{\\partial MSE(\\hat{y}, y)}{\\partial \\hat{y}}\\times\\frac{\\partial\\hat{y}(in_{j})}{\\partial in_{j}}\\times\\frac{\\partial in_{j}}{\\partial w_{j}}$$\n",
1405+
"\n",
1406+
"Solving this equation, we have:\n",
1407+
"\n",
1408+
"$$\\frac{\\partial MSE(\\hat{y}, y)}{\\partial w_{j}} = (\\hat{y} - y)\\times{\\hat{y}}'(in_{j})\\times a_{j}$$\n",
1409+
"\n",
1410+
"Remember that $\\hat{y}$ is the activation function applied to a neuron in our hidden layer, therefore $$\\hat{y} = sigmoid(\\sum_{i=1}^{num\\_neurons}w_{i}\\times a_{i})$$\n",
1411+
"\n",
1412+
"Also $a$ is the input generated by feeding the input layer variables into the hidden layer.\n",
1413+
"\n",
1414+
"We can use the same technique for the weights in the input layer as well. After we have the gradients for both weights, we use gradient descent to update the weights of the network."
1415+
]
1416+
},
1417+
{
1418+
"cell_type": "markdown",
1419+
"metadata": {},
1420+
"source": [
1421+
"### Implementation\n",
1422+
"\n",
1423+
"First, we feed-forward the examples in our neural network. After that, we calculate the gradient for each layer weights. Once that is complete, we update all the weights using gradient descent. After running these for a given number of epochs, the function returns the trained Neural Network."
1424+
]
1425+
},
1426+
{
1427+
"cell_type": "code",
1428+
"execution_count": 4,
1429+
"metadata": {
1430+
"collapsed": true
1431+
},
1432+
"outputs": [],
1433+
"source": [
1434+
"%psource BackPropagationLearner"
1435+
]
1436+
},
1437+
{
1438+
"cell_type": "code",
1439+
"execution_count": 4,
1440+
"metadata": {},
1441+
"outputs": [
1442+
{
1443+
"name": "stdout",
1444+
"output_type": "stream",
1445+
"text": [
1446+
"0\n"
1447+
]
1448+
}
1449+
],
1450+
"source": [
1451+
"iris = DataSet(name=\"iris\")\n",
1452+
"iris.classes_to_numbers()\n",
1453+
"\n",
1454+
"nNL = NeuralNetLearner(iris)\n",
1455+
"print(nNL([5, 3, 1, 0.1]))"
1456+
]
1457+
},
1458+
{
1459+
"cell_type": "markdown",
1460+
"metadata": {},
1461+
"source": [
1462+
"The output should be 0, which means the item should get classified in the first class, \"setosa\". Note that since the algorithm is non-deterministic (because of the random initial weights) the classification might be wrong. Usually though it should be correct.\n",
1463+
"\n",
1464+
"To increase accuracy, you can (most of the time) add more layers and nodes. Unfortunately the more layers and nodes you have, the greater the computation cost."
14521465
]
14531466
},
14541467
{

0 commit comments

Comments
 (0)