<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Siddhartha Dutta on Medium]]></title>
        <description><![CDATA[Stories by Siddhartha Dutta on Medium]]></description>
        <link>https://medium.com/@siddydutta?source=rss-c224efebc1b6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IFbuk0_ZprxkaIM2LgQAkA.png</url>
            <title>Stories by Siddhartha Dutta on Medium</title>
            <link>https://medium.com/@siddydutta?source=rss-c224efebc1b6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:52:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@siddydutta/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Implementing the XOR Gate using Backpropagation in Neural Networks]]></title>
            <link>https://medium.com/data-science/implementing-the-xor-gate-using-backpropagation-in-neural-networks-c1f255b4f20d?source=rss-c224efebc1b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1f255b4f20d</guid>
            <category><![CDATA[artificial-neural-network]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Siddhartha Dutta]]></dc:creator>
            <pubDate>Thu, 21 Mar 2019 11:07:41 GMT</pubDate>
            <atom:updated>2022-05-26T07:04:54.768Z</atom:updated>
            <content:encoded><![CDATA[<p>Implementing logic gates using neural networks help understand the mathematical computation by which a neural network processes its inputs to arrive at a certain output. This neural network will deal with the XOR logic problem. An XOR (exclusive OR gate) is a digital logic gate that gives a true output only when both its inputs differ from each other. The truth table for an XOR gate is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*01idVj7sVw2ZnGZFapvW4A.png" /><figcaption>Truth Table for XOR</figcaption></figure><p>The goal of the neural network is to classify the input patterns according to the above truth table. If the input patterns are plotted according to their outputs, it is seen that these points are not linearly separable. Hence the neural network has to be modeled to separate these input patterns using <em>decision planes.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*_HLG8KlGJFZxtWoB8J1kFA.png" /><figcaption>XOR, Graphically</figcaption></figure><h3>THE NEURAL NETWORK MODEL</h3><p>As mentioned before, the neural network needs to produce two different decision planes to linearly separate the input data based on the output patterns. This is achieved by using the concept of <em>hidden layers</em>. The neural network will consist of one input layer with two nodes (X1,X2); one hidden layer with two nodes (since two decision planes are needed); and one output layer with one node (Y). Hence, the neural network looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*qXt_iBvWods-FOvTldxYFw.png" /><figcaption>The Neural Network Model to solve the XOR Logic (from: <a href="https://stopsmokingaids.me/">https://stopsmokingaids.me/</a>)</figcaption></figure><h3>THE SIGMOID NEURON</h3><p>To implement an XOR gate, I will be using a Sigmoid Neuron as nodes in the neural network. The characteristics of a Sigmoid Neuron are:</p><p>1. Can accept real values as input.</p><p>2. The value of the activation is equal to the weighted sum of its inputs <br>i.e. ∑wi xi</p><p>3. The output of the sigmoid neuron is a function of the sigmoid function, which is also known as a logistic regression function. The sigmoid function is a continuous function which outputs values between 0 and 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*R4twuYNUKXVzsvgOGkPZsA.png" /><figcaption>The Sigmoidal Curve</figcaption></figure><h3>THE LEARNING ALGORITHM</h3><p>The information of a neural network is stored in the interconnections between the neurons i.e. the weights. A neural network learns by updating its weights according to a learning algorithm that helps it converge to the expected output. The learning algorithm is a principled way of changing the weights and biases based on the loss function.</p><ol><li>Initialize the weights and biases randomly.</li><li>Iterate over the data<br> i. Compute the predicted output using the sigmoid function<br> ii. Compute the loss using the square error loss function<br>iii. W(new) = W(old) — α ∆W<br> iv. B(new) = B(old) — α ∆B</li><li>Repeat until the error is minimal</li></ol><p>This is a fairly simple learning algorithm consisting of only arithmetic operations to update the weights and biases. The algorithm can be divided into two parts: the <em>forward pass</em> and the <em>backward pass</em> also known as <em>“backpropagation.”</em></p><p>Let’s implement the first part of the algorithm. We’ll initialize our weights and expected outputs as per the truth table of XOR.</p><pre>inputs = np.array([[0,0],[0,1],[1,0],[1,1]])<br>expected_output = np.array([[0],[1],[1],[0]])</pre><p>Step 1: To initialize the weights and biases with random values</p><pre>import numpy as np</pre><pre>inputLayerNeurons, hiddenLayerNeurons, outputLayerNeurons = 2,2,1</pre><pre>hidden_weights = np.random.uniform(size=(inputLayerNeurons,hiddenLayerNeurons))<br>hidden_bias =np.random.uniform(size=(1,hiddenLayerNeurons))</pre><pre>output_weights = np.random.uniform(size=(hiddenLayerNeurons,outputLayerNeurons))<br>output_bias = np.random.uniform(size=(1,outputLayerNeurons))</pre><p>The forward pass involves compute the predicted output, which is a function of the weighted sum of the inputs given to the neurons:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/1*m6Bs9A8FvWbqCa7nqn_GWg.png" /><figcaption>The Sigmoid Function</figcaption></figure><p>Where Σwx + b is known as the activation.</p><pre>def sigmoid (x):<br>    return 1/(1 + np.exp(-x))</pre><pre>hidden_layer_activation = np.dot(inputs,hidden_weights)<br>hidden_layer_activation += hidden_bias<br>hidden_layer_output = sigmoid(hidden_layer_activation)</pre><pre>output_layer_activation = np.dot(hidden_layer_output,output_weights)<br>output_layer_activation += output_bias<br>predicted_output = sigmoid(output_layer_activation)</pre><p>This completes a single forward pass, where our predicted_output needs to be compared with the expected_output. Based on this comparison, the weights for both the hidden layers and the output layers are changed using backpropagation. Backpropagation is done using the Gradient Descent algorithm.</p><h3>GRADIENT DESCENT</h3><p>The loss function of the sigmoid neuron is the squared error loss. If we plot the loss/error against the weights we get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*rNDygHX0Ds1In2mBE1ZC4g.png" /><figcaption>Error/Loss vs Weights Graph</figcaption></figure><p>Our goal is to find the weight vector corresponding to the point where the error is minimum i.e. the minima of the error gradient. And here is where calculus comes into play.</p><h3>THE MATH BEHIND GRADIENT DESCENT</h3><p>Error can be simply written as the difference between the predicted outcome and the actual outcome. Mathematically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/139/1*bSE-d1xTHdPMc_woav7m-w.png" /></figure><p>where <em>t</em> is the targeted/expected output &amp; <em>y</em> is the predicted output</p><p>However, is it fair to assign different error values for the same amount of error? For example, the absolute difference between -1 and 0 &amp; 1 and 0 is the same, however the above formula would sway things negatively for the outcome that predicted -1. To solve this problem, we use square error loss.(Note modulus is not used, as it makes it harder to differentiate). Further, this error is divided by 2, to make it easier to differentiate, as we’ll see in the following steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*FawfyTR5ga85aFd8Jhbbjg.png" /><figcaption>Squared Error Loss</figcaption></figure><p>Since, there may be many weights contributing to this error, we take the partial derivative, to find the minimum error, with respect to each weight at a time. The change in weights are different for the output layer weights (W31 &amp; W32) and different for the hidden layer weights (W11, W12, W21, W22).<br>Let the outer layer weights be wo while the hidden layer weights be wh.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/1*pZ8p9GnRNp7pI9_LtD755A.png" /></figure><p>We’ll first find ∆W for the outer layer weights. Since the outcome is a function of activation and further activation is a function of weights, by chain rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*lQmnCwjEwo0MdVjvRswCHg.png" /></figure><p>On solving,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*BRGgm_r1yfh0_Zwd6QMfiQ.png" /><figcaption>Change in the outer layer weights</figcaption></figure><p>Note that for Xo is nothing but the output from the hidden layer nodes.<br>This output from the hidden layer node is again a function of the activation and correspondingly a function of weights. Hence, the chain rule expands for the hidden layer weights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*ytRh9SKcH5beWceMUNyLFw.png" /></figure><p>Which comes to,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*l7rYNFhoaD5GDU_oNo3XwQ.png" /><figcaption>Change in the hidden layer weights</figcaption></figure><blockquote>NOTE: Xo can also be considered to be Yh i.e. the output from the hidden layer is the input to the output layer. Xh is the input to the hidden layer, which are the actual input patterns from the truth table.</blockquote><p>Let’s then implement the backward pass.</p><pre>def sigmoid_derivative(x):<br>    return x * (1 - x)</pre><pre>#Backpropagation<br>error = expected_output - predicted_output<br>d_predicted_output = error * sigmoid_derivative(predicted_output)<br> <br>error_hidden_layer = d_predicted_output.dot(output_weights.T)<br>d_hidden_layer = error_hidden_layer * sigmoid_derivative(hidden_layer_output)</pre><pre>#Updating Weights and Biases<br>output_weights += hidden_layer_output.T.dot(d_predicted_output) * lr<br>output_bias += np.sum(d_predicted_output,axis=0,keepdims=True) * lr<br>hidden_weights += inputs.T.dot(d_hidden_layer) * lr<br>hidden_bias += np.sum(d_hidden_layer,axis=0,keepdims=True) * lr</pre><p>This process is repeated until the predicted_output converges to the expected_output. It is easier to repeat this process a certain number of times (iterations/epochs) rather than setting a threshold for how much convergence should be expected.</p><h3>PYTHON IMPLEMENTATION</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f48ca554342182e9f72d4990ab2c214/href">https://medium.com/media/2f48ca554342182e9f72d4990ab2c214/href</a></iframe><p>Choosing the number of epochs and the value of the learning rate decides two things: how accurate the model is, and how fast did the model take to compute the final output. The concept of <em>hyperparameter tuning</em> is a whole subject by itself. <br>The output with epochs = 10,000 and learning rate = 0.1 is:</p><pre>Output from neural network after 10,000 epochs: <br>[0.05770383] [0.9470198] [0.9469948] [0.05712647]</pre><p>Hence, the neural network has converged to the expected output:<br>[0] [1] [1] [0]. The epoch vs error graph shows how the error is minimized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*lZ0aYuPWcDaGUgbgSFE90A.png" /></figure><h3>Resources</h3><ol><li>An Introduction to Neural Networks by Kevin Gurney</li><li><a href="https://www.analyticsvidhya.com/blog/2017/05/neural-network-from-scratch-in-python-and-r/">https://www.analyticsvidhya.com/blog/2017/05/neural-network-from-scratch-in-python-and-r/</a></li><li>Thanks to <a href="https://www.codecogs.com/latex/eqneditor.php">https://www.codecogs.com/latex/eqneditor.php</a> for converting LaTeX Equations to PNGs used in this article.</li></ol><p>I would love to hear about any feedback/suggestions! Connect with me <a href="https://www.linkedin.com/in/siddharthapratimdutta/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1f255b4f20d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/implementing-the-xor-gate-using-backpropagation-in-neural-networks-c1f255b4f20d">Implementing the XOR Gate using Backpropagation in Neural Networks</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>