<?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 Prachi Patel on Medium]]></title>
        <description><![CDATA[Stories by Prachi Patel on Medium]]></description>
        <link>https://medium.com/@prachipatel2597?source=rss-88a4b7f8f0f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PcApLiB9nbsO6oyzUlU3GA.jpeg</url>
            <title>Stories by Prachi Patel on Medium</title>
            <link>https://medium.com/@prachipatel2597?source=rss-88a4b7f8f0f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:10:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prachipatel2597/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[The Test Set Trap: When Your Model Looks Better Than It Really Is]]></title>
            <link>https://medium.com/@prachipatel2597/the-test-set-trap-when-your-model-looks-better-than-it-really-is-62bd5bec6d32?source=rss-88a4b7f8f0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/62bd5bec6d32</guid>
            <category><![CDATA[crossvalidation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Prachi Patel]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 23:17:32 GMT</pubDate>
            <atom:updated>2026-11-26T23:17:32.145Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*HvBnC9YX3MkLr8n48h9XOA.png" /></figure><p>We’ve explored several learning algorithms so far, including linear regression, logistic regression, and even deep learning. But knowing how these algorithms work is only part of the picture.</p><p>The bigger question is: <strong>How do we know whether we’re using the right model, and how do we evaluate whether it’s actually doing a good job?</strong></p><p>Let’s say we’re building a model to predict housing prices. We’ve chosen linear regression, added regularization, and trained our model using the following cost function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*Aby8IIR9DdLTH-7qBovfJg.png" /></figure><p>But after training the model, we realize that it’s making large prediction errors. What should we do next?</p><p>We have several options:</p><ul><li>Get more training examples.</li><li>Try using a smaller set of features.</li><li>Collect additional features that might help improve predictions.</li><li>Add polynomial features.</li><li>Try increasing or decreasing the regularization parameter, lambda.</li></ul><p>All of these are possible ways to improve a model. But how do we know which one is actually worth trying?</p><p>We don’t want to spend hours adding more features or changing parameters only to discover that none of it improves the model.</p><p><strong>The key is to run diagnostic tests that help us understand what’s going wrong before deciding what to change.</strong></p><p>Let’s see how we can do that.</p><h3>Evaluating a Model’s Performance</h3><p>Let’s continue with our housing-price prediction example.</p><p>Suppose we’re predicting the price of a house using four features:</p><ul><li>(x_1): Size of the house in square feet</li><li>(x_2): Number of bedrooms</li><li>(x_3): Number of floors</li><li>(x_4): Age of the house in years</li></ul><p>Imagine that we fit a fourth-order polynomial model using just five training examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jSoEJ94_ATOkaJGe86j3aw.png" /></figure><p>Because we have a fourth-order polynomial and only five training examples, the model can fit the training data extremely well.</p><p>At first glance, this might look like a great result. After all, the predictions are very close to the actual housing prices.</p><p>But there’s a problem.</p><p>Even though the model fits the training data well, it might perform very poorly when we give it new examples that it hasn’t seen before.</p><p>This is an example of <strong>Overfitting</strong>.</p><p>If we were predicting housing prices using just one feature, such as the size of the house, we could plot the function and see that the curve is extremely wiggly. That would give us a visual indication that the model might not generalize well.</p><p>But what happens when we have four features?</p><p>Now we’re dealing with a function that depends on four variables, and visualizing it becomes much more difficult.</p><p>So, how do we determine whether our model is doing well when we have multiple features and can’t simply look at a graph?</p><p>We need a more systematic way to evaluate its performance.</p><p>And that’s where <strong>training and test sets</strong> come in.</p><h3>Splitting Our Data into Training and Test Sets</h3><p>Let’s say we have a dataset containing 10 examples.</p><p>Instead of using all 10 examples to train our model, we can split the dataset into two smaller groups:</p><ul><li><strong>Training set:</strong> 70% of our data (7 examples)</li><li><strong>Test set:</strong> 30% of our data (3 examples)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LuyukdW5LwzyVnxDD7ANlw.png" /></figure><p>We use the training set to learn the parameters of our model, such as (w) and (b). Once the model has been trained, we use the test set to evaluate how well it performs on examples it hasn’t seen during training.</p><p>Let’s look at how we represent these two datasets mathematically.</p><h3>The Training Set</h3><p>We can represent our training examples as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*L7fO-NbW85fQUp7dyKG95A.png" /></figure><p>where m_train represents the training examples. In our case m_train = 7 and these are the seven examples that our algorithm will use to learn the model parameters.</p><h3>The Test Set</h3><p>Similarly, we represent the test examples as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*k0HG7ZllTU9s-41R6JpESg.png" /></figure><p>Here, m_test represents the number of test examples. In our example m_test = 3 and these three examples are kept separate from the training process. We use them only after training to see how well our model performs on unseen data.</p><p>Now let’s see how we actually calculate the training and test errors.</p><h3>Evaluating Regression Models</h3><p>Let’s start with linear regression using a squared error cost function.</p><h3>Step 1: Train the Model</h3><p>First, we train our model using the training set by minimizing the regularized cost function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*a7b-KyP7Uy9xRR8mD2BjEA.png" /></figure><p>This is the same cost function we’ve seen before. It contains:</p><ul><li>The squared error term, which measures how far the predictions are from the actual values.</li><li>The regularization term, which penalizes large parameter values to help prevent overfitting.</li></ul><p>By minimizing this cost function, we obtain the parameters (w) and (b) that our model will use to make predictions.</p><p>If we are using linear regression with a squared error cost. We start off by minimizing the cost function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/88/1*rigozBcRy0tFAg1QMaOQ0g.png" /></figure><p>This is the usual cost function minimized over w, b of the squared error cost</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*CSKb3FuKmUwXatoisQJnfw.png" /></figure><p>plus the regularization term</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*lN4V8d4HEdsZk-Wkc9SiIg.png" /></figure><h3>Step 2: Calculate the Test Error</h3><p>Once we’ve trained the model, we want to know how well it performs on the test set.</p><p>To do this, we calculate the test error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*P-oSVXCaSTRp2AZ7YG9Pfg.png" /></figure><p>This is essentially the average squared prediction error across all the examples in the test set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/72/1*zCpV9z8uQbpo85YXTKdpOw.png" /></figure><p>Here <em>m_</em>test​ represents the number of test examples. We then sum the squared errors for all test examples, from i = 1 to <em>i </em>= <em>m_</em>test​, to calculate the test cost</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*VeCFCNSZxqyHx0vx9YAblw.png" /></figure><p>It represents the squared difference between the model’s predicted price for the i th test example and the actual price of that house.</p><p>Notice something important: <strong>the test error does not include the regularization term.</strong></p><p>Why?</p><p>Because we’re interested in measuring how accurately our model predicts the actual housing prices on unseen data. We aren’t trying to penalize the model’s parameter values again. We simply want to know how large its prediction errors are.</p><h3>Step 3: Calculate the Training Error</h3><p>We can also calculate the training error using a similar formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*uCUvCnT9OhSWvZTWGi5IYQ.png" /></figure><p>This measures the average squared prediction error across all the examples in the training set.</p><p>It’s worth distinguishing between two things:</p><ul><li>The <strong>regularized cost function</strong> is what we minimize to learn the model parameters.</li><li>The <strong>training and test errors</strong> help us evaluate how well the trained model predicts the actual values.</li></ul><p>They serve different purposes.</p><h3>What Do the Training and Test Errors Tell Us?</h3><p>Now let’s go back to our earlier housing-price prediction example. Since our model fits the training data extremely well, J_{train}(w,b) will be low, potentially close to zero.</p><p>But what happens if we introduce a few additional examples from our test set that the algorithm hasn’t seen or trained on?</p><p>The model might not perform nearly as well. There could be a large difference between the housing prices predicted by the algorithm and the actual housing prices.</p><p>As a result, the test error, J_{test}(w,b), will be high.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HKF6UqrsecndWXTrA4Q7cQ.png" /></figure><p>And this tells us something important.</p><p>Even though our model performs extremely well on the training data, it doesn’t generalize well to new examples.</p><p>In other words, <strong>our model is overfitting</strong>.</p><p>This is exactly why evaluating a model using only its training error can be misleading. A model might appear to be doing a fantastic job simply because it has learned the training examples very closely.</p><p>The test set gives us a better indication of how well it performs on data it hasn’t encountered during training.</p><p>So far, we’ve looked at regression using a squared error cost function.</p><p>But what happens when we’re working with a classification problem?</p><h3>Evaluating Classification Models</h3><p>Let’s say we’re building a model to classify handwritten digits into two categories: 0 and 1.</p><p>We can use logistic regression to predict whether a handwritten digit belongs to class 0 or class 1.</p><p>As before, we first train our model by minimizing the logistic regression cost function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*QerJPJkSN7V8peaWG79cYA.png" /></figure><p>Once we’ve trained the model and obtained the parameters (w) and (b), we can evaluate its performance on the test set.</p><h3>Calculating the Test and Train Error Using Logistic Loss</h3><p>One way to calculate the test error is to use the average logistic loss across all the test examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*Lh9Zuiup33E8j7PcdZxygw.png" /></figure><p>This is the average over our test example which is 30% of the data that wasn’t in the training set.</p><p>Similarly, we can calculate the training error using the average logistic loss across the training examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*MrBNGEq_l89RBna4tWIfRg.png" /></figure><p>These formulas tell us how well our model’s predicted probabilities match the actual class labels.</p><p>However, when we’re working with classification problems, there’s another way to evaluate performance that’s often easier to interpret.</p><p>Instead of calculating the average logistic loss, we can simply measure <strong>the fraction of examples our model classified incorrectly</strong>.</p><p>Let’s see what that means.</p><h3>Measuring the Fraction of Incorrect Predictions</h3><p>Remember that logistic regression gives us a probability between 0 and 1.</p><p>For binary classification, we typically use a threshold of 0.5:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*vKXLu9OqhpA5dA4t95iABQ.png" /></figure><p>So, if the model predicts a probability of 0.8, we classify the example as 1. If it predicts 0.3, we classify it as 0.</p><p>Now, imagine that we run our trained model on every example in the test set.</p><p>For each example, we compare the predicted class y^ with the actual class y.</p><p>If they match, the prediction is correct.</p><p>If they don’t match, the prediction is incorrect.</p><p>We can then calculate the fraction of incorrectly classified examples:</p><p>For example, suppose we have 100 examples in our test set and our model incorrectly classifies 10 of them.</p><p>J_{test} = 10/100 = 0.10 = 10%.</p><p>So our test error is 10%.</p><p>In our handwritten-digit example, this means counting how many times the model predicts 1 when the actual answer is 0, or predicts 0 when the actual answer is 1.</p><p>We can calculate the same fraction for the training set as well.</p><p>This gives us two useful measurements:</p><ul><li><strong>Training error:</strong> The fraction of training examples the model classified incorrectly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*Tc2cxb75IZP_XrCst34IXg.png" /></figure><ul><li><strong>Test error:</strong> The fraction of test examples the model classified incorrectly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/106/1*KmMFjaFONvfvUEEahiqDsA.png" /></figure><p>This approach is often called the <strong>classification error rate</strong>.</p><p>It gives us a straightforward way to understand how frequently our model makes incorrect predictions.</p><p>This is one of the key steps in being able to automatically choose the best model for a given application.</p><p>And with a little more refinement, we’ll be able to build an approach that automatically chooses the degree of polynomial that gives us the best outcome.</p><h3>Model Selection: Training, Cross-Validation, and Test Sets</h3><p>We saw how to use a test set to evaluate the performance of a model. But if we refine this approach a little further, we can use it to automatically choose a good model for a given application.</p><p>Earlier, we saw that the parameters (w) and (b) are fitted to the training set. However, the training error isn’t necessarily a good indicator of how well the algorithm will perform on new examples that it hasn’t seen before.</p><p>Let’s look at the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H9risbTUrglOklpMnzvFuA.png" /></figure><p>We can see that the training error is almost zero. But this doesn’t necessarily mean that the model will perform well on new data. In fact, the training error could be much lower than the actual generalization error, which is the average error the model makes on new examples that aren’t part of the training set.</p><p>The performance of an algorithm on examples it hasn’t been trained on gives us a better indication of how well it will generalize to new data.</p><p>So, how can we use this idea to automatically choose a model for a given machine learning application?</p><h3>Choosing a Model Using the Test Set</h3><p>Let’s say we’re fitting a function to predict housing prices, or we’re working on some other regression problem.</p><p>We might consider fitting a linear model like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*exF8EskFeivYCKB8BsM11A.png" /></figure><p>This is a first-order polynomial, and we’re going to use (d=1) to denote that we’re fitting a first-order polynomial.</p><p>If we fit this model to our training set, we’ll obtain the parameters (w) and (b). We can then calculate J_{test}(w,b) to estimate how well the model will generalize to new data.</p><p>We can use a superscript &lt;1&gt; to indicate that we’re referring to the first-order polynomial</p><p>Similarly, we can fit other polynomial models of different degrees:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3L5F5WbccwophgDLxNNhw.png" /></figure><p>One approach we could take is to calculate the test error for all these models and choose the one with the lowest J_test.</p><p>For example, let’s say:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*s1G6aZEHC8LPXLjKjRXXCA.png" /></figure><p>gives us the lowest value, we might conclude that (d=5), or the fifth-order polynomial, is the best model and choose it for our application.</p><p>If we then want to report how well this model performs, we could report its test set error. Although this might seem like a reasonable approach, it actually has a flaw.</p><p>The test error we obtain is likely to be an overly optimistic estimate of the generalization error. In other words, it is likely to be lower than the actual generalization error.</p><p>Why?</p><p>Because we used the test set itself to decide which degree of polynomial, (d), to choose.</p><p>Earlier, we saw that fitting the parameters (w) and (b) to the training data could give us an overly optimistic estimate of the generalization error if we evaluated the model on that same training data.</p><p>Similarly, if we use the test set to choose the degree of polynomial, then the test set error is no longer an unbiased evaluation of how well our model generalizes. We have effectively used the test set to make a decision about the model, which means the test error can end up being lower than the actual generalization error.</p><p>So, this isn’t the best procedure, and we should avoid using the test set to select our model.</p><p>Instead, if we want to automatically choose a model and decide which degree of polynomial to use, we introduce something called the <strong>validation set</strong>, also known as the <strong>cross-validation set.</strong></p><h3>Introducing the Cross-Validation Set</h3><p>Instead of splitting our data into just a training set and a test set, we now introduce a third subset called the cross-validation set.</p><p>Let’s take our earlier dataset and split it into three parts:</p><ul><li><strong>Training set:</strong> 60% of the data</li><li><strong>Cross-validation set:</strong> 20% of the data</li><li><strong>Test set:</strong> 20% of the data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*4OewoT_W3HZYHioSFkztHA.png" /></figure><p>The cross-validation set is an additional dataset that we use to evaluate and compare different models. It helps us cross-check how well the different models perform before deciding which one to use.</p><p>Now that we have these three subsets of data, we can calculate the training error, cross-validation error, and test error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*aMytwiC2VL-eojcJhvJMMg.png" /></figure><p>Notice that the regularization term is not included in any of these error calculations.</p><p>The cross-validation error is simply the average squared error across all the examples in the cross-validation set, where (m_{cv}) represents the number of cross-validation examples.</p><p>The cross-validation error is also commonly referred to as the <strong>validation error</strong> or <strong>dev error</strong>.</p><h3>Using the Cross-Validation Set for Model Selection</h3><p>Now that we have our three subsets of data, we can use them to select a model.</p><p>Let’s say we have 10 different models, each representing a polynomial of a different degree.</p><p>We can fit the parameters for the first-order polynomial, all the way to the tenth order polynomial, but instead of evaluating them on the test set we evaluate them on the cross validation set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yx-qbl_Fe_8Zkn7xMqz1Yw.png" /></figure><p>To choose our model, we simply look at which polynomial has the lowest cross-validation error.</p><p>Let’s say the fourth-order polynomial gives us the lowest value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*c6f7_kiuJWv1qqa1FIhPGA.png" /></figure><p>In that case, we choose the fourth-order polynomial as the model we’ll use for our application.</p><p>But how do we know how well this model will perform on new data?</p><p>That’s where our third subset, the test set, comes in.</p><p>Once we’ve chosen the fourth-order polynomial using the cross-validation set, we can evaluate its performance on the test set by calculating:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*8IonAQpgRa5Q6DFNdU1-yA.png" /></figure><p>Throughout this entire process, we fitted the parameters (w) and (b) using the training set, chose the degree of polynomial (d) using the cross-validation set, and only used the test set at the very end to evaluate our final model.</p><p>This means that we haven’t used the test set to fit our parameters or make decisions about which model to choose.</p><p>As a result, J_test gives us a much fairer estimate of how well our chosen model, with parameters (w^&lt;4&gt;,b^&lt;4&gt;) will generalize to new data.</p><p>This gives us a better procedure for model selection and helps us decide which degree of polynomial to use for our regression model.</p><h3>Applying Model Selection to Neural Networks</h3><p>This model selection procedure isn’t limited to polynomial regression. We can also use it to choose between different neural network architectures.</p><p>For example, if we’re building a model to recognize handwritten digits, we might consider three different neural network architectures:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-o-JZ2J6viBidbReyp1zNg.png" /></figure><p>Suppose we want to decide how many layers our neural network should have and how many units we should use in each layer.</p><p>We can train all three of these models using the training set, resulting in the parameters for the first, second and third model respectively</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*Le0K1irHYXMp6cwDHWRJsw.png" /></figure><p>We can then evaluate the performance of each neural network using the cross-validation set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*PpgkoCgVh4d_20UsxQcvGQ.png" /></figure><p>Since this is a classification problem, one of the most common ways to calculate the cross-validation error is to use the fraction of cross-validation examples that the algorithm misclassified.</p><p>We calculate this error for all three models and choose the one with the lowest cross-validation error.</p><p>For example, if:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*Ik-0grg924qdD3MMQw6KRg.png" /></figure><p>has the lowest cross-validation error, we would choose the second neural network architecture and use the parameters that were trained for that model.</p><p>Finally, if we want to estimate how well this chosen neural network will generalize to new data, we evaluate it using the test set.</p><h3>Why We Keep the Test Set Separate</h3><p>In machine learning, it’s considered best practice to make decisions about our model, such as fitting parameters or choosing the model architecture, using only the training set and the cross-validation set.</p><p>We should avoid using the test set while making these decisions.</p><p>It is only after we’ve chosen our final model that we evaluate it using the test set.</p><p>Since we haven’t used the test set to make decisions about the model, it gives us a much fairer estimate of how well our model generalizes to new data, without the same overly optimistic bias that can arise when we use the test set for model selection.</p><p>Now that we know how to evaluate learning algorithms and even automatically choose a model, let’s explore some of the diagnostics we can use to understand how our models are performing, starting with <strong>bias and variance</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62bd5bec6d32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Do Neural Networks Actually Learn? The Math Behind Backpropagation]]></title>
            <link>https://medium.com/@prachipatel2597/how-do-neural-networks-actually-learn-the-math-behind-backpropagation-8dc01deb3369?source=rss-88a4b7f8f0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dc01deb3369</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computational-graphs]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Prachi Patel]]></dc:creator>
            <pubDate>Sun, 11 Oct 2026 20:55:21 GMT</pubDate>
            <atom:updated>2026-10-11T20:55:21.272Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cXl6Zbt9Gs8SoJU1mn9-zQ.png" /></figure><p>In TensorFlow, we can specify a neural network architecture that takes an input x and computes an output. We can also specify the cost function that tells us how well the network is performing.</p><p>TensorFlow then takes care of the rest. It uses <strong>backpropagation</strong> to compute the derivatives of the cost function with respect to the network’s parameters and then uses an optimization algorithm such as <strong>gradient descent or Adam</strong> to update those parameters.</p><p>Backpropagation is one of the key algorithms that makes training neural networks possible.</p><p>But how does it actually work?</p><p>To understand the basic idea, let’s start with a much simpler example.</p><h3>A Simple Cost Function</h3><p>Imagine that we have a very simple cost function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*8sLnbQ_cDAWyEr39I32J7A.png" /></figure><p>Normally, a model would have both weights ww and biases bb, but let’s ignore bb for now so that we can focus on the main idea.</p><p>Suppose: w = 3 then:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*1CXX4dc8rK6EzZ2mw6SY7A.png" /></figure><p>Let’s say we increase w by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*IgsGsqY_QPc8fXsYmmhbmg.png" /></figure><p>Our new value of w is: w = 3 + 0.001 = 3.001.</p><p>So the new value of the cost function is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*qMFl662Bslh74GoqF98X_g.png" /></figure><p>Originally, our cost was <strong>9</strong>, and now it is approximately <strong>9.006</strong>.</p><p>So when we increased ww by only <strong>0.001</strong>, the cost increased by approximately: 0.0060</p><p>Notice something interesting: 0.006 ≈ 6×0.001</p><p>This tells us that, around w = 3, a tiny increase in ww produces an increase in J(w) that is approximately <strong>6 times larger</strong>.</p><p>And this is exactly what the <strong>derivative</strong> tells us.</p><p>For our function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*Y4QwuKPxdGPybP6mYB6zXQ.png" /></figure><p>the derivative is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*8XWdjFMk8_mw-efPmv-Srg.png" /></figure><p>At w = 3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*EPDxXY8wTSwgLvZEKAU3JA.png" /></figure><p>So the derivative tells us:</p><blockquote><strong><em>If we increase w by a very small amount, J(w) will increase by approximately 6 times that amount.</em></strong></blockquote><h3>What If We Use a Different epsilon ϵ?</h3><p>Let’s try:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*IaGYPNysW_XEOz1kcnfFZw.png" /></figure><p>Now: w = 3 + 0.002 = 3.002</p><p>and therefore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*bhfT9g-7VlVZvcoKotJEeQ.png" /></figure><p>The cost has increased from: 9→9.012004</p><p>So the increase is: 0.012004</p><p>Again, notice that: 6 × 0.002 = 0.012</p><p>Our actual increase is <strong>0.012004</strong>, which is extremely close to 0.012.</p><p>The tiny difference comes from the fact that 0.0020.002 is still not infinitesimally small.</p><p>As ϵ epsilon gets smaller and smaller, our approximation becomes more accurate.</p><h3>What Does the Derivative Really Tell Us?</h3><p>The important idea isn’t the specific value of ϵ epsilon. It’s the <strong>relationship between the change in J(w) and the change in w</strong>.</p><p>For our example, that relationship is approximately:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/139/1*YjZk6miBID9pINJHjfjRMg.png" /></figure><p>So, around w = 3:</p><blockquote><strong><em>For every tiny increase of 1 unit in w, the cost J(w) changes by approximately 6 units.</em></strong></blockquote><p>More generally, the derivative tells us the <strong>rate at which one quantity changes when another quantity changes by a very small amount</strong>.</p><p>And this idea is incredibly important for neural networks.</p><p>During training, we need to know:</p><blockquote><strong><em>If I change this particular parameter slightly, how much will the cost function change?</em></strong></blockquote><p>That is exactly the type of information we need to update the weights and biases using gradient descent.</p><p>And while our example only has one parameter w, a real neural network can have thousands or millions of parameters.</p><p>So how do we efficiently calculate these derivatives for all those parameters?</p><p>That’s where the <strong>chain rule and backpropagation</strong> come in.</p><h3>So, What Is a Derivative?</h3><p>We’ve seen that if w increases by a small amount ϵ epsilon, the value of J(w) also changes.</p><p>Informally, we can say:</p><blockquote><em>If w goes up by ϵ epsilon, then J(w) goes up by approximately k × ϵ</em></blockquote><p>In our earlier example, when w = 3, we found that k = 6. We call this value <strong>the derivative of J with respect to w</strong>.</p><p>In other words:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*ClKbuu665O-GbFQCvgP8cw.png" /></figure><p>The derivative tells us <strong>how sensitive J(w) is to changes in w</strong>.</p><h3>How Does This Connect to Gradient Descent?</h3><p>If you remember gradient descent, we repeatedly use the following rule to update the parameter w_j:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*lyl781RCh5yAObxCzJpY-w.png" /></figure><p>where α\alpha is the learning rate.</p><p>So, what does gradient descent actually do?</p><p>Look at the derivative in the update rule.</p><ul><li>If the derivative is <strong>small</strong>, the update to w_j will be small.</li><li>If the derivative is <strong>large</strong>, the update to w_j will be larger.</li><li>If the derivative is <strong>positive</strong>, gradient descent decreases w_j.</li><li>If the derivative is <strong>negative</strong>, gradient descent increases w_j.</li></ul><p>And this actually makes intuitive sense.</p><p>If the derivative is small, it means that changing w_j doesn’t have a very big effect on the cost J. So there isn’t much reason to make a large change to w_j.</p><p>But if the derivative is large, it means that even a small change in w_j can cause a relatively large change in the cost. In that situation, making a larger update to w_j can help us reduce the cost more quickly.</p><p>So the derivative gives gradient descent a sense of <strong>which direction to move and how strongly to move</strong>.</p><p>Let’s look at a few examples.</p><h3>Example 1: What If w=2?</h3><p>Let’s say: J(w) = w²</p><p>If w = 2: J(2) = 2² = 4</p><p>Now suppose w increases by a small amount: ϵ = 0.001</p><p>So: w = 2.001</p><p>and: J(2.001) = (2.001)² = 4.004001</p><p>The value of J(w) increased from 4 to 4.004001</p><p>That’s an increase of: 4.004001 − 4 = 0.004001</p><p>which is approximately: 4×0.0014</p><p>So in this case, the derivative is approximately <strong>4</strong>.</p><p>And we’ll soon see that the exact derivative is indeed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/105/1*owMweWD2DBIq9bgoffEkgw.png" /></figure><p>when w = 2</p><h3>Example 2: What If w = -3?</h3><p>Now let’s look at something a little more interesting.</p><p>Again: J(w) = w²</p><p>But this time: w = −3</p><p>So: J(-3) = (-3)² = 9</p><p>Now let’s increase w by: ϵ = 0.001</p><p>Since we’re <strong>increasing</strong> w, we go from: −3 → −2.999</p><p>Now: J(-2.999) = (-2.999)² = 8.994001</p><p>Notice what happened.</p><p>Even though we increased w, the value of J(w) <strong>decreased</strong>: 9→8.994001</p><p>The change in J is: 8.994001− 9 = −0.005999</p><p>which is approximately: −6×0.001</p><p>So the derivative is approximately: −6</p><p>This is interesting because when w = 3, the derivative was +6, but when w = −3, the derivative is −6.</p><p>The function is the same in both cases: J(w) = w²</p><p>but the derivative is different because <strong>the derivative depends on where you are on the function</strong>.</p><h3>Visualizing the Derivative</h3><p>We can also understand all of this by looking at the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*SlxLzZGF9cZw1NfjH81afQ.png" /></figure><p>If we plot: J(w) = w²</p><p>with w on the x-axis and J(w) on the y-axis, we get a parabola.</p><p>We can see that:</p><ul><li>When w = 3, J(w) = 9</li><li>When w = 2, J(w) = 4</li><li>When w = −3, J(w) = 9</li></ul><p>But there’s something else we can learn from this graph.</p><p>In calculus, the derivative at a particular point corresponds to the <strong>slope of the line that just touches the curve at that point</strong>. This is called the <strong>tangent line</strong>.</p><p>Remember that slope is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*21ZlGKPyjDKf6uWM17w3PA.png" /></figure><p>So at:</p><ul><li>w = 3, the slope is 6</li><li>w = 2, the slope is 4</li><li>w = −3, the slope is −6</li></ul><p>These slopes are exactly the derivatives we calculated earlier.</p><p>So we now have another way to think about a derivative:</p><blockquote><strong><em>The derivative tells us the slope of the function at a particular point.</em></strong></blockquote><h3>The Derivative Depends on w</h3><p>Notice something interesting.</p><p>Our function hasn’t changed: J(w) = w²</p><p>But its derivative changes depending on the value of w.</p><p>Using calculus, we can find the derivative of w²:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*JFs2aJrENbt41nFiOSV3cQ.png" /></figure><p>So:</p><p>when w = 3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*kIcz-nZ2oyKJkf59KGDhMQ.png" /></figure><p>when w = 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*zLfrzBYG9BfRphjk6ad37Q.png" /></figure><p>when w = −3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*B8d4ws17zlPcVdezsdcaHQ.png" /></figure><p>This matches exactly what we observed using the small ϵ epsilon approach.</p><p>So the derivative isn’t just a single number associated with the function. <strong>Its value can change depending on where we are on the function.</strong></p><h3>What If the Function Is Different?</h3><p>So far, we’ve only looked at: J(w) = w²</p><p>But what if: J(w) = w³ or J(w) = w or: J(w) = 1/w</p><p>How do we find their derivatives?</p><p>We could calculate them manually using calculus rules, but Python has libraries that can do this for us.</p><p>One useful library is <strong>SymPy</strong>.</p><pre>import sympy as sp<br><br>J, w = sp.symbols(&#39;J w&#39;)</pre><p>Now let’s say: J(w) = w²</p><pre>J = w**2</pre><p>To find the derivative of J with respect to w, we can use:</p><pre>dJ_dw = sympy.diff(J,w)</pre><p>which gives:</p><pre>2*w</pre><p>So SymPy tells us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/133/1*FOBm3_ela2zoJXWHBwugLQ.png" /></figure><p>But what if we want the actual value of the derivative when w = 2?</p><p>We can substitute w = 2:</p><pre>dJ_dw.subs([(w,2)])</pre><p>which gives:</p><pre>4</pre><p>So when w = 2, the derivative is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/141/1*jLhJoe1AtL6LHebsea7yjw.png" /></figure><h3>Let’s Try a Few More Functions</h3><p>Now we can try some other functions.</p><p>If: J(w) = w³</p><p>then:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*1GkryRPRkcfCi2BtiOpUVw.png" /></figure><p>So when w = 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*79rE0jmL32p4-vhedNITAg.png" /></figure><p>If: J(w) = w</p><p>then:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/124/1*N5zkod_32SU60boYLuZcRg.png" /></figure><p>And if:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*W-uiRxRsBSe0UItxrU-GwQ.png" /></figure><p>then:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/174/1*QwpYiEkstEdGkqR6T98D2w.png" /></figure><p>So when w = 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/139/1*qU3NonENVui1wRhJraO6zg.png" /></figure><p>SymPy can calculate all of these for us.</p><h3>We Can Also Check It Manually</h3><p>Of course, we don’t have to rely only on SymPy.</p><p>We can use the same approach we used earlier: increase ww by a small ϵ epsilon, calculate how much J(w) changes, and use that to approximate the derivative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*wvxU7pAmWYjXImcggFIf-g.png" /></figure><p>And we get the same basic idea:</p><blockquote><em>If w goes up by a small amount ϵ epsilon, then J(w) changes by approximately k × ϵ.</em></blockquote><p>The important thing to remember is that <strong>k depends on two things</strong>:</p><ol><li>The function J(w)</li><li>The current value of w</li></ol><p>And that value of k is what we call the <strong>derivative</strong>.</p><p>This idea becomes especially important for neural networks because we don’t just have one parameter w. We can have thousands or even millions of parameters. We need an efficient way to calculate how changing each parameter affects the cost — and that’s where <strong>backpropagation and the computational graphs </strong>come in.</p><h3>Computation Graphs and Backpropagation</h3><p>The <strong>computation graph</strong> is one of the key ideas behind deep learning. It provides a way to break a complicated computation into a series of smaller steps. It is also the basic structure that TensorFlow uses to compute derivatives for neural networks.</p><p>Let’s see how this works with a very simple example.</p><h3>Building a Computation Graph</h3><p>Consider a very simple neural network with just <strong>one input unit and one output unit</strong>. There are no hidden layers.</p><p>The network takes an input x, applies a linear activation, and produces the output a: a = w x + b</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*QE_iXR_SBo82jWp3IBbKFw.png" /><figcaption>This is essentially <strong>linear regression expressed as a neural network with one output unit</strong>.</figcaption></figure><p>Since we’re using a linear activation function: a = g(z) = z</p><p>For this example, let’s use the following cost function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*MTgxgi0XBB6tXRRWwqBMWQ.png" /></figure><p>To keep things simple, we’ll work with just <strong>one training example</strong>.</p><p>Let’s say: x = −2, y = 2 and our parameters are: w = 2, b = 8</p><p>Our goal is to calculate the cost J, and then figure out how changing w and b would change that cost.</p><h3>Forward Propagation Through the Computation Graph</h3><p>Remember that J is ultimately a function of the parameters w and b.</p><p>We can break the calculation into several smaller steps.</p><h3>Step 1: Calculate c=wx</h3><p>First, we multiply w and x. Let’s call the result c: c = wx</p><p>Using our values: c = (2)(−2) = −4</p><h3>Step 2: Calculate a = c + b</h3><p>Next, we calculate the output a: a = c + b</p><p>So: a = −4+8 = 4</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*ANT7vIBcongZmdZYMLFsPQ.png" /></figure><h3>Step 3: Calculate d=a−y</h3><p>Now we need to calculate the difference between our prediction and the actual value.</p><p>Let’s call this d: d = a−y</p><p>Therefore: d = 4−2 = 2</p><h3>Step 4: Calculate the Cost</h3><p>Finally, we calculate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/133/1*UZrDbWsrqQskiXaGIC3vKw.png" /></figure><p>So:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/147/1*vc1Gcbq65-QTVy501plrEA.png" /></figure><p>And that’s our <strong>computation graph</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*78siDRm0wOxOykRham9JYg.png" /></figure><p>It shows us, step by step, how we go from the inputs and parameters all the way to the final cost J: w, x → c → a → d→ J</p><p>This is <strong>forward propagation</strong>: we move through the computation graph from left to right, calculating each value until we arrive at the cost.</p><p>But now comes the more interesting question:</p><blockquote><strong><em>How do we calculate the derivatives of J with respect to w and b?</em></strong></blockquote><h3>Backpropagation: Working Backward</h3><p>We already saw that <strong>forward propagation moves from left to right</strong> and is used to calculate the cost J.</p><p>Backpropagation does the opposite.</p><p>It moves <strong>from right to left</strong> through the computation graph and calculates how each variable affects the final cost.</p><p>Let’s start at the very last step of forward propagation.</p><p>The final step was:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*PvIqJxx0ozPQvDtYH2b0rw.png" /></figure><p>So our first question during backpropagation is:</p><blockquote><strong><em>How much does J change if d changes?</em></strong></blockquote><h3>Step 1: Calculate dJ/dd</h3><p>We know that: d = 2</p><p>Suppose d increases by a very small amount: ϵ = 0.001</p><p>So d changes from: 2→2.0012</p><p>The new value of J is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*noCiWzWqeG1GmWDl2KGHfw.png" /></figure><p>which is approximately: 2.002001</p><p>So J has increased by approximately: 0.002</p><p>And: 0.002 = 2 × 0.001</p><p>In other words:</p><blockquote><em>If d increases by ϵ epsilon, J increases by approximately 2ϵ.</em></blockquote><p>Therefore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/102/1*1hbAqvo7L8RdU3nww-NJuA.png" /></figure><p>This is the <strong>first step of backpropagation</strong>.</p><p>We start at the end of the computation graph and determine how sensitive J is to its immediate input, d.</p><h3>Step 2: Calculate ∂J/∂a</h3><p>Now we move one step backward.</p><p>We know: d = a − y</p><p>We want to know:</p><blockquote><strong><em>How much does J change when a changes?</em></strong></blockquote><p>Suppose a increases by: ϵ = 0.001</p><p>Since: a = 4</p><p>we now have: a = 4.001</p><p>Because: d = a − y</p><p>and y=2: d = 4.001−2 = 2.001</p><p>So when a increases by 0.001, d also increases by 0.001</p><p>But we already know something important:</p><blockquote><em>When d increases by 0.001, J increases by approximately 2(0.001).</em></blockquote><p>Therefore, when a increases by 0.001, J also increases by approximately: 2(0.001)</p><p>So:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/103/1*BrCpaOjgrYEQjtdqmeB3tg.png" /></figure><p>And this is where we can see the <strong>chain rule</strong> beginning to appear.</p><p>We can write:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*CrdOdR6FQkLh84xmJfA4NA.png" /></figure><p>We already know:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/1*5-cYjzYHLx0AHCAX3iiLqg.png" /></figure><p>And because: d = a − y</p><p>a small change in a produces the same-sized change in d:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*ZvQvrVXh2qIX5xRnI3z-rw.png" /></figure><p>Therefore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*iai0a5Q57cQmNDPr9ci7Fw.png" /></figure><p>This is the key idea behind the <strong>chain rule</strong>:</p><blockquote><em>To find out how a change in a affects J, we can break the calculation into smaller steps: first see how a affects d, and then see how d affects J.</em></blockquote><h3>Step 3: Calculate ∂J/∂c</h3><p>Let’s continue moving backward through the computation graph.</p><p>We know: a = c + b</p><p>Now let’s ask:</p><blockquote><strong><em>How much does J change when cc changes?</em></strong></blockquote><p>Suppose cc increases by: 0.001</p><p>Currently: c = −4</p><p>so the new value is: c = −3.999</p><p>Since: a = c + b</p><p>we get: a = −3.999+8 = 4.001</p><p>So when c increases by 0.001, a also increases by 0.001</p><p>We already calculated that: ∂J/∂a = 2</p><p>Therefore, when a increases by 0.001, J increases by approximately: 2(0.001)</p><p>So: ∂J/∂c = 2</p><p>Using the chain rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*0oJ8he-ihc5Mz2xxoSa_Zg.png" /></figure><p>Since:</p><p>∂J/∂a = 2 and ∂a/∂c ​= 1</p><blockquote>we get: ∂c/∂J​=2×1=2</blockquote><h3>Step 4: Calculate ∂J/∂b</h3><p>Now let’s calculate the derivative with respect to b.</p><p>Again: a = c + b</p><p>Suppose b increases by 0.001.</p><p>Since a = c + b , a will also increase by 0.001.</p><p>And we already know that an increase of 0.001 in aa causes J to increase by approximately: 2(0.001)</p><p>Therefore: ∂J/∂b=2</p><p>Using the chain rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*o7NmYp426xVUYExKnOxpcQ.png" /></figure><p>∂J/∂b = 1×2 = 2</p><h3>Step 5: Calculate ∂J/∂w</h3><p>Finally, we’ve reached w.</p><p>We know: c = wx</p><p>and we want to answer:</p><blockquote><strong><em>How much does J change when w changes?</em></strong></blockquote><p>Suppose w increases by: 0.001</p><p>Currently: w = 2</p><p>so: w = 2.001</p><p>Since: c = wx and: x = −2</p><p>the new value of c is: c = (2.001)(−2) = −4</p><p>Notice something important.</p><p>When w increased by 0.001, c <strong>decreased</strong> by: 0.002</p><p>or: −2(0.001)</p><p>We already know: ∂J/∂c = 2</p><p>So a decrease of 0.002 in c causes J to change by approximately:</p><p>2(−0.002) = −0.004</p><p>Therefore, when w increases by 0.001, J decreases by approximately 0.004.</p><p>So: ∂J/∂w = −4</p><p>And once again, we can express this using the chain rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*YNDQDf_ZvEkM-HWo5CPabw.png" /></figure><p>We know:</p><p>∂J/∂c = 2</p><p>and because: c = wx</p><p>we have: ∂c/∂w = −2</p><p>Therefore: ∂J/∂w = 2(−2) = −4</p><p>And there we have it: <strong>∂J/∂w = −4</strong></p><h3>Putting It All Together</h3><p>Let’s step back and look at the entire process.</p><p>Our forward propagation was: w, x → c → a → d → J</p><p>We started with: w = 2,x = −2,b = 8,y = 2</p><p>and calculated: c = −4, a = 4, d = 2, J = 2</p><p>Then, during backpropagation, we moved from right to left:</p><p>J → d → a → c → w, b</p><p>and calculated:</p><p>∂J/∂d = 2, ∂J/∂a = 2, ∂J/∂c = 2, ∂J/∂b = 2, ∂J/∂w = −4</p><p>So the entire process looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*ybb-V9WvLSVoOP-Efee5Fw.png" /></figure><h3>Let’s Verify the Result</h3><p>We can also verify that our result for ∂J/∂w is correct by substituting the values into the original equation.</p><p>Remember:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*IzNEualgzVdbxbw2W4IO8A.png" /></figure><p>where: a = c + b and: c = wx</p><p>So:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*qY-lp_HurfQSnLL7C5o_Pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*38GPG4dp6u7Fp5idAlDIHQ.png" /></figure><p>If we differentiate this expression with respect to w, using the chain rule, we get the same result:</p><p><strong>∂J/∂w = −4</strong></p><p>So our backpropagation calculation checks out.</p><h3>So, What Is the Point of Backpropagation?</h3><p>At this point, you might be wondering:</p><blockquote><strong><em>Why go through all these steps? Why not just calculate the derivative directly?</em></strong></blockquote><p>For this tiny example, we absolutely could.</p><p>But real neural networks are much more complicated.</p><p>A neural network can contain <strong>thousands, millions, or even billions of parameters</strong>. Calculating the derivative of the cost with respect to every parameter independently would be extremely inefficient.</p><p>The power of backpropagation comes from the fact that it <strong>reuses derivatives that have already been calculated</strong>.</p><p>For example, when calculating: ∂J/∂w</p><p>we need: ∂J/∂c</p><p>But to calculate: ∂c/∂J​</p><p>we needed: ∂J/∂a</p><p>And to calculate: ∂J/∂a</p><p>we needed: ∂d/∂J​</p><p>So rather than starting from scratch for every parameter, backpropagation works backward through the computation graph and <strong>reuses these intermediate derivatives</strong>.</p><p>For example, we calculated: ∂J/∂a = 2 only once.</p><p>But that result can then be used to calculate the derivatives with respect to both b and c.</p><p>This reuse is what makes backpropagation so efficient.</p><h3>Why This Matters for Large Neural Networks</h3><p>Suppose a computation graph has n intermediate nodes and p parameters.</p><p>Without efficiently reusing intermediate derivatives, we could end up doing work proportional to roughly: n × p</p><p>But backpropagation allows us to compute the necessary derivatives in roughly: n + p steps.</p><p>For a small example, the difference might not seem important.</p><p>But imagine a neural network with:</p><ul><li><strong>10,000 nodes</strong></li><li><strong>100,000 parameters</strong></li></ul><p>Doing something proportional to n×p would mean an enormous amount of computation.</p><p>Backpropagation instead allows us to efficiently move backward through the computation graph, calculate intermediate derivatives once, and reuse them to obtain the derivatives for many different parameters.</p><p><strong>That efficiency is one of the main reasons backpropagation is so important to modern deep learning.</strong></p><h3>Forward Propagation vs. Backpropagation</h3><p>So we can now summarize the entire idea:</p><p><strong>Forward propagation</strong> moves from left to right through the computation graph and is used to calculate the output and ultimately the cost J.</p><p><strong>Backpropagation</strong> moves from right to left and uses the chain rule to efficiently calculate the derivatives of JJ with respect to the parameters.</p><p>And once we have those derivatives, <strong>gradient descent or an optimizer such as Adam can use them to update the parameters and reduce the cost</strong>.</p><p>So the overall training process is essentially:</p><p>Forward Propagation → Compute Cost → Backpropagation → Update Parameters</p><h3>Conclusion</h3><p>At this point, we’ve covered some of the most important ideas behind how a neural network actually <strong>learns</strong>.</p><p>We started with forward propagation, where the network takes an input, passes it through the different layers, and produces a prediction. We then saw how the cost function tells us how far that prediction is from the actual value.</p><p>From there, we explored <strong>derivatives and gradient descent</strong> to understand how the parameters should be changed to reduce the cost. Finally, we saw how <strong>computation graphs, the chain rule, and backpropagation</strong> work together to efficiently calculate those derivatives, even when a neural network has thousands or millions of parameters.</p><p>But there is still an important question we haven’t answered:</p><blockquote><strong><em>How do we know whether our trained model actually works well on data it has never seen before?</em></strong></blockquote><p>A model can perform extremely well on the data it was trained on, but that doesn’t necessarily mean it will make good predictions on new data.</p><p>That’s where <strong>training, validation, and test sets</strong> come in.</p><p>In the next chapter, we’ll take our data and learn how to split it into <strong>training, validation, and test sets</strong>, how each split is used, and why keeping these datasets separate is so important when evaluating a machine learning model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dc01deb3369" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Logistic Regression Isn’t Enough Anymore]]></title>
            <link>https://medium.com/@prachipatel2597/why-logistic-regression-isnt-enough-anymore-599ff03c95b7?source=rss-88a4b7f8f0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/599ff03c95b7</guid>
            <category><![CDATA[softmax]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[adam-optimizer]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[multiclass-classification]]></category>
            <dc:creator><![CDATA[Prachi Patel]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 18:10:25 GMT</pubDate>
            <atom:updated>2026-08-10T18:12:14.167Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*PyUwSw50CWPArfgwdYlx1g.png" /></figure><h3>Multiclass Classification</h3><p>So far, every classification problem we’ve looked at has been a <strong>binary classification problem</strong>. That means our model only had to choose between <strong>two possible outcomes</strong> — for example, <strong>0 or 1</strong>, <strong>yes or no</strong>, or <strong>spam or not spam</strong>.</p><p>But what happens when there are <strong>more than two possible classes</strong>?</p><p>That’s where <strong>multiclass classification</strong> comes in.</p><p>A <strong>multiclass classification problem</strong> is one where the output can belong to <strong>one of several discrete categories</strong>, rather than just two.</p><p>In other words, instead of predicting only <strong>0 or 1</strong>, our model might have to choose between <strong>3, 5, 10, or even hundreds of possible classes</strong>.</p><p>Let’s go back to our handwritten digit recognition example.</p><p>Earlier, we simplified the problem by asking our neural network to distinguish only between the digits <strong>0</strong> and <strong>1</strong>.</p><p>But imagine you’re building a system to automatically read <strong>ZIP codes</strong> or <strong>postal codes</strong> from envelopes.</p><p>In that case, recognizing just <strong>0</strong> and <strong>1</strong> clearly isn’t enough.</p><p>Your model needs to recognize <strong>all ten digits</strong>, from <strong>0 through 9</strong>.</p><p>Similarly, suppose we’re building a machine learning model to help diagnose patients.Instead of simply predicting whether a patient is <strong>healthy</strong> or <strong>unhealthy</strong>, the model might need to determine <strong>which disease</strong> the patient has.</p><p>For example, the output could belong to one of several possible disease categories.</p><p>Both of these are examples of <strong>multiclass classification problems</strong>.</p><p>The important thing to remember is that <strong>multiclass classification is still a classification problem</strong>.</p><p>The output <strong>y</strong> doesn’t take any arbitrary value like it would in a regression problem.</p><p>Instead, it can only belong to one of a <strong>fixed number of discrete classes</strong>.</p><h3>From Binary Classification to Multiclass Classification</h3><p>Let’s compare this with what we learned earlier.</p><p>For <strong>binary classification</strong>, suppose we have a dataset with two input features.</p><p>Using logistic regression, we learned to estimate the probability that: y=1</p><p>given the input features <strong>x</strong>.</p><p>Since there were only two possible classes, predicting the probability of <strong>y=1 </strong>automatically gave us the probability of <strong>y=0</strong> as well.</p><p>Now consider a multiclass classification problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9a_1P0To7QPxzirS_TS6JQ.png" /></figure><p>Instead of having just two classes, imagine our dataset contains <strong>four different categories</strong>, represented by:</p><ul><li>Circle</li><li>Cross</li><li>Diamond</li><li>Square</li></ul><p>Now our model isn’t just deciding whether <strong>y=0</strong> or <strong>y=1</strong>.</p><p>Instead, it must determine which of the <strong>four possible classes</strong> the input belongs to.</p><p>In other words, it needs to estimate the probability that:</p><ul><li>y=1</li><li>y=2</li><li>y=3</li><li>y=4</li></ul><p>Rather than using logistic regression, neural networks handle this type of problem using the <strong>Softmax activation function</strong>.</p><p>Softmax allows the model to assign a probability to <strong>every possible class</strong>, and the class with the highest probability becomes the model’s final prediction.</p><p>As we’ll see next, Softmax is one of the key ideas that allows neural networks to move beyond simple binary classification and tackle much more complex real-world problems, from recognizing handwritten digits to identifying diseases and classifying thousands of different objects in an image.</p><h3>Softmax Regression: Extending Logistic Regression to Multiple Classes</h3><p>Earlier, we learned about <strong>logistic regression</strong>, which works well when there are only <strong>two possible classes</strong>.</p><p>But what if our model has to choose between <strong>more than two classes</strong>?</p><p>That’s exactly what <strong>Softmax regression</strong> is designed for.</p><p>In fact, you can think of <strong>Softmax regression as a natural extension of logistic regression</strong>.</p><p>Instead of predicting the probability of just two classes, Softmax predicts the probability of <strong>multiple classes</strong>.</p><p>Let’s see how.</p><h3>Revisiting Logistic Regression</h3><p>Remember that logistic regression is used for <strong>binary classification</strong>, where the output <strong>y</strong> can only take two values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/1*JNJ22fgYi010unsxTMG-6Q.png" /></figure><p>The first thing we compute is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*TKuTZras0yg_WH_LI6wjkg.png" /></figure><p>We then pass z through the sigmoid activation function to obtain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*zztNp0d8N0g-EmvndAlaEg.png" /></figure><p>In other words, <strong>a</strong> is the probability that the input belongs to class <strong>1</strong>.</p><p>Suppose our model predicts: a=0.75</p><p>This means the model believes there’s a <strong>75% chance</strong> that: y=1</p><p>Since there are only two possible classes, the probability of the other class must be: P( y = 0 | x) = 1–0.75 = 0.25</p><p>Notice something important here.</p><p>The probabilities always add up to <strong>1</strong>: 0.75 + 0.25 = 1</p><p>We can also write these probabilities as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*M4c3ulAIbLC4JXHuz9BvPQ.png" /></figure><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*BTvQTCq9GbHQMO6c4fbm3A.png" /></figure><h3>Generalizing to Softmax Regression</h3><p>Now suppose our classification problem has <strong>four possible classes</strong> instead of two.</p><p>Our output can now be: y=1, 2, 3, 4</p><p>Instead of computing just one probability, Softmax computes one score for <strong>each class</strong>.</p><p>First, we calculate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*f9Rn2eTE1rzN4HIhV6lrVw.png" /></figure><p>Here:</p><ul><li>w_1,w_2,w_3,w_4​ are the weight vectors for each class.</li><li>b_1,b_2,b_3,b_4​ are the corresponding bias terms.</li></ul><p>Next, we apply the <strong>Softmax function</strong> to convert these scores into probabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*OdtUxqtrhLPF0XqqCIbRYA.png" /></figure><p>Here a_1 will be interpreted as the algorithm’s estimate of the chance of y = 1 given the input features x, similarly for a_2, a_3 and a_4:</p><p>The resulting activations are interpreted as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*pVyWVrELKQkzrLXRvYAEbw.png" /></figure><p>Each activation tells us how likely the model thinks the input belongs to that particular class.</p><p>Once the neural network learns the appropriate values for the weights and biases, it can estimate the probability of every possible class for any new input.</p><p>For example, suppose the model predicts:</p><p>a1=0.32, a2=0.15, a3=0.25</p><p>What would a4​ be?</p><p>Since the probabilities must always add up to <strong>1</strong>, we simply calculate:</p><p>a4=1−(0.32+0.15+0.25)=1−0.72=0.28</p><p>Once again, notice that:</p><p>0.32+0.15+0.25+0.28 = 1</p><p>This is one of the defining properties of the Softmax function.</p><blockquote><strong><em>The probabilities of all possible classes always add up to 1.</em></strong></blockquote><h3>The General Softmax Formula</h3><p>So far, we’ve assumed there are only <strong>four classes</strong>.</p><p>But what if we have <strong>10 classes</strong>, <strong>100 classes</strong>, or even <strong>1,000 classes</strong>?</p><p>Fortunately, the Softmax equation easily generalizes.</p><p>If there are <strong>N </strong>possible classes, the probability of class <strong>j</strong> is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*toZ1QBPbJuV8Wp_wNL4K9g.png" /></figure><p>Here:</p><ul><li><strong>j</strong> refers to the specific class whose probability we’re computing.</li><li><strong>k</strong> runs over <strong>all possible classes</strong>, from:1, 2, 3, …N</li></ul><p>Earlier, we only had four classes, so k ranged from 1 to 4.</p><p>No matter how many classes there are, one important property always holds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*LFEGE43la-L_bSxXmAGKxg.png" /></figure><p>This ensures that the outputs form a valid probability distribution.</p><h3>How Is Softmax Related to Logistic Regression?</h3><p>You might be wondering:</p><blockquote><strong><em>If Softmax works for any number of classes, why do we even need logistic regression?</em></strong></blockquote><p>The answer is simple.</p><p>If there are only <strong>two classes</strong>: N=2</p><p>then the Softmax equation reduces to logistic regression.</p><p>In other words, logistic regression is simply a <strong>special case of Softmax regression</strong> where there are only two possible outputs.</p><p>That’s why Softmax is often described as:</p><blockquote><strong><em>The generalization of logistic regression to multiclass classification problems.</em></strong></blockquote><h3>Cost Function for Softmax Regression</h3><p>Just like logistic regression, Softmax also needs a way to measure <strong>how good or bad its predictions are</strong>.</p><p>For logistic regression, we predicted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*dTXhK2VVTaFt8ygSopb3lQ.png" /></figure><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*Tc1yqMYEgWwOx50R0r0_yQ.png" /></figure><p>The loss for a single training example was:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*na6S9AkCcL0UAspoq5KbeA.png" /></figure><p>This equation becomes much easier to understand if we consider the two possible cases separately.</p><p>If y = 1, then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*ETEPdXzKYHu0akfNjUEm-A.png" /></figure><p>because the second term becomes zero.</p><p>On the other hand, if: y=0, then:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*4-fQCeeNNegg1n4PZ_-XAg.png" /></figure><p>because the first term becomes zero.</p><p>So, the loss simply penalizes the model whenever it assigns a low probability to the correct class.</p><p>Finally, just like we did for logistic regression, we compute the <strong>cost function</strong> by averaging the loss across all the training examples.</p><p>In other words:</p><blockquote><strong><em>The cost function for Softmax regression is simply the average loss over the entire training dataset.</em></strong></blockquote><p>Earlier, we saw how Softmax regression predicts the probability of each possible class.</p><p>The model computes the probabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*wO0q3vckHiE8e-lh78O7Rw.png" /></figure><p>After computing these probabilities, the next question is:</p><blockquote><strong><em>How do we know whether the predictions are good or bad?</em></strong></blockquote><p>Just like logistic regression, we need a <strong>loss function</strong> that tells us how far our predictions are from the correct answer.</p><p>For Softmax regression, the loss for a single training example is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*hNm-XZ7CjlI92hz3ASQGLg.png" /></figure><p>This equation might look a little intimidating at first, but it’s actually very simple once we break it down.</p><p>Suppose the correct class for a training example is: y=1</p><p>Then the loss becomes: −log⁡(a_1)</p><p>If instead the correct class is: y=2</p><p>then the loss is simply: −log⁡(a_2)</p><p>Similarly,</p><ul><li>If y=3, the loss is −log⁡(a_3)</li><li>If y=4, the loss is −log⁡(a_4)</li></ul><p>And in general, if the true class is j, then the loss is:</p><p>Loss= − log⁡(a_j)</p><p>Notice something important here.</p><p>For each training example, <strong>only one class is actually correct</strong>.</p><p>That means we compute <strong>only one term</strong> in the loss function — the one corresponding to the true class.</p><p>For example, if: y=2</p><p>we compute only: −log⁡(a_2)</p><p>We completely ignore terms like: −log⁡(a_1), −log⁡(a_3), −log⁡(a_4)</p><p>because those aren’t the correct labels for this particular training example.</p><h3>What Does This Loss Function Look Like?</h3><p>Let’s look at the graph of: −log⁡(a_j)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*hbnjRPtuKTvqp5HXDV5d5A.png" /></figure><p>The graph tells us exactly how the model is rewarded or penalized.</p><p>Suppose the correct class is j.</p><p>If the model predicts: a_j≈1</p><p>then the loss is very close to <strong>0</strong>.</p><p>That’s exactly what we want — the model was highly confident and it was correct.</p><p>Now suppose the model predicts: a_j=0.5</p><p>The loss becomes larger because the model isn’t very confident about the correct class.</p><p>Finally, if: a_j is very close to <strong>0</strong>, the loss becomes extremely large.</p><p>In other words:</p><ul><li><strong>Large probability for the correct class → Small loss</strong></li><li><strong>Small probability for the correct class → Large loss</strong></li></ul><p>This encourages the neural network to assign <strong>as much probability as possible to the correct class</strong> during training.</p><p>Once we’ve computed the loss for every training example, we average them together to obtain the <strong>cost function</strong>, which is what the learning algorithm tries to minimize.</p><h3>Advanced Optimization</h3><p>So far, we’ve been using <strong>gradient descent</strong> to train our neural networks.</p><p>Gradient descent is one of the most important optimization algorithms in machine learning and forms the foundation of many algorithms, including <strong>linear regression</strong>, <strong>logistic regression</strong>, and the early implementations of neural networks.</p><p>But in practice, we rarely use plain gradient descent by itself anymore.</p><p>Over the years, researchers have developed optimization algorithms that can train neural networks <strong>more efficiently</strong> and often <strong>converge much faster</strong>.</p><p>One of the most popular of these algorithms is called <strong>Adam</strong>.</p><h3>A Quick Recap of Gradient Descent</h3><p>Remember the gradient descent update rule?</p><p>Each parameter is updated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*Fe9KAxUfu-dPmhvd81wKBw.png" /></figure><p>where:</p><ul><li><strong>J</strong> is the cost function.</li><li><strong>alpha α</strong> is the learning rate.</li><li>The partial derivative tells us which direction reduces the cost the fastest.</li></ul><p>The learning rate controls how large each step is as we move toward the minimum of the cost function.</p><p>But choosing the right learning rate isn’t always easy.</p><h3>When the Learning Rate Is Too Small</h3><p>Imagine we’re trying to minimize a cost function that looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*bIT7xkIEumrIC4KbzIWJSg.png" /></figure><p>The lowest point is located at the center of the contours.</p><p>Suppose we start somewhere far away from the minimum.</p><p>If the learning rate is very small, gradient descent takes tiny steps toward the center.</p><p>Each update moves in almost exactly the same direction.</p><p>Eventually we’ll reach the minimum — but it may take a very long time.</p><p>At this point, it’s natural to ask:</p><blockquote><strong><em>Why can’t we just increase the learning rate and take larger steps?</em></strong></blockquote><p>That’s exactly the kind of problem the <strong>Adam optimizer</strong> is designed to solve.</p><p>If Adam notices that the optimization is consistently moving in roughly the same direction, it can automatically adapt the step size so that learning progresses faster.</p><h3>When the Learning Rate Is Too Large</h3><p>Now let’s look at the opposite problem.</p><p>Suppose the learning rate is much too large.</p><p>Instead of gradually approaching the minimum, gradient descent might overshoot it on every update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*fzS3LEZ-d1_9wEBO4v8bdA.png" /></figure><p>The optimization keeps bouncing back and forth across the minimum instead of settling down.</p><p>In this situation, the learning rate is clearly too large.</p><p>The Adam optimizer can recognize this behavior as well.</p><p>Instead of continuing to overshoot the minimum, Adam automatically adjusts the step sizes, allowing the optimization to settle more smoothly toward the lowest point of the cost function.</p><h3>Why Adam Is So Popular</h3><p>The biggest advantage of Adam is that it <strong>automatically adapts the learning rate while training</strong>.</p><p>If learning is progressing too slowly, Adam can effectively increase the step sizes.</p><p>If the optimization starts oscillating because the steps are too large, Adam can reduce them.</p><p>As a result, training is often:</p><ul><li>Faster</li><li>More stable</li><li>Less sensitive to the initial learning rate</li></ul><p>This is why you’ll see the <strong>Adam optimizer</strong> used as the default optimizer in many TensorFlow and PyTorch examples.</p><p>In the next section, we’ll see how to use the Adam optimizer in TensorFlow and how it fits into the process of training a neural network.</p><h3>The Adam Optimizer</h3><p>In the previous section, we saw that choosing the right learning rate is important.</p><p>If the learning rate is <strong>too small</strong>, gradient descent takes tiny steps and learning becomes slow.</p><p>If the learning rate is <strong>too large</strong>, gradient descent can overshoot the minimum and keep oscillating back and forth.</p><p>So, wouldn’t it be nice if the algorithm could automatically adjust the learning rate for us?</p><p>That’s exactly what the <strong>Adam optimizer</strong> does.</p><p>Adam stands for <strong>Adaptive Moment Estimation</strong>, and it’s one of the most widely used optimization algorithms in deep learning today.</p><p>The key idea behind Adam is that it <strong>doesn’t use a single learning rate for the entire model</strong>.</p><p>Instead, it keeps track of <strong>a separate learning rate for every parameter</strong> in the neural network.</p><p>Suppose our model has the following parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*Zab0DmCGyHc22rnkNnCq-g.png" /></figure><p>That means our model has <strong>11 parameters</strong> in total.</p><p>Rather than using one learning rate alphaα, Adam effectively adapts the update for each parameter individually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*w-WV_0qpIcof-hdbWP7e1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*BZnof8DlUGp1QcwoTgNiyA.png" /></figure><p>This allows each parameter to learn at its own pace instead of forcing every parameter to take exactly the same-sized step.</p><h3>How Does Adam Decide?</h3><p>Think back to the two situations we looked at earlier.</p><h3>Case 1: Moving Consistently in One Direction</h3><p>Suppose one of the parameters, say w_j, keeps moving in roughly the same direction during training.</p><p>This usually means we’re making steady progress toward the minimum, but perhaps we’re taking steps that are smaller than necessary.</p><p>In this situation, Adam can effectively <strong>increase the learning rate for that parameter</strong>, allowing it to move more quickly toward the minimum.</p><p>This is similar to the first contour plot we saw earlier, where gradient descent kept taking many small steps in nearly the same direction.</p><h3>Case 2: Oscillating Back and Forth</h3><p>Now suppose another parameter keeps bouncing back and forth between updates.</p><p>This usually indicates that the learning rate for that parameter is too large.</p><p>Instead of continuing to overshoot the minimum, Adam can <strong>reduce the learning rate for that parameter</strong>, allowing the optimization to settle down more smoothly.</p><p>This is exactly what happened in our second contour plot, where gradient descent kept oscillating around the minimum.</p><h3>Why Is Adam So Effective?</h3><p>The beauty of Adam is that <strong>every parameter is treated independently</strong>.</p><p>Some parameters may need to move quickly.</p><p>Others may need to move more cautiously.</p><p>Instead of forcing every parameter to share the same learning rate, Adam automatically adapts the updates for each one.</p><p>This often leads to:</p><ul><li>Faster convergence</li><li>More stable training</li><li>Less manual tuning of the learning rate</li></ul><p>That’s one of the reasons Adam has become the default optimizer for many deep learning applications.</p><h3>Using Adam in TensorFlow</h3><p>The best part is that using Adam in TensorFlow requires just one extra line of code.</p><p>If we look at the code, it should look very familiar. It is almost identical to the TensorFlow code we’ve been using throughout this series.</p><p>The main difference is that we’ve added one extra argument to the compile() function—we&#39;re now telling TensorFlow which optimization algorithm we&#39;d like to use.</p><p>In this case, we’re using the <strong>Adam optimizer</strong>.</p><pre>model = Sequential([<br>    tf.keras.layers.Dense(units=25, activation=&#39;sigmoid&#39;),<br>    tf.keras.layers.Dense(units=15, activation=&#39;sigmoid&#39;),<br>    tf.keras.layers.Dense(units=10, activation=&#39;linear&#39;)<br>])<br><br>model.compile(<br>    optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3),<br>    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)<br>)<br><br>model.fit(X, Y, epochs=100)</pre><p>You’ll also notice that we’ve specified an initial learning rate:</p><pre>learning_rate = 1e-3</pre><p>Although Adam automatically adapts the learning rate for each parameter during training, it still needs an <strong>initial starting point</strong>. Here, we’ve chosen a default learning rate of: 10^{-3} = 0.001</p><p>Think of this as the learning rate that Adam starts with before it begins adjusting the individual learning rates for each parameter.</p><p>In practice, it’s often worth experimenting with a few different initial learning rates to see which one allows your model to learn the fastest. Depending on the problem you’re trying to solve, a slightly larger or smaller starting value may lead to better performance.</p><p>The nice thing about Adam, however, is that it’s much more forgiving than standard gradient descent.</p><p>With vanilla gradient descent, choosing the wrong learning rate can make training painfully slow or even prevent the model from converging altogether. Adam, on the other hand, adapts the learning rate as training progresses, making it much more robust to the initial value that we choose.</p><p>Because of this, Adam has become the optimizer of choice for many deep learning applications.</p><p>So, if you’re ever unsure which optimization algorithm to use for training your neural network, <strong>Adam is usually a safe and reliable default</strong>. It’s one of the reasons you’ll see it used in so many TensorFlow examples, research papers, and production machine learning systems today.</p><h3>Our goal is to train a neural network to determine whether this ECG signal indicates a heart condition.Types of Layers</h3><p>So far, every neural network we’ve built has used only one type of layer: the <strong>Dense layer</strong>.</p><p>In a dense layer, <strong>every neuron is connected to every neuron in the previous layer</strong>. In other words, each neuron receives <strong>all</strong> the activations from the previous layer as its input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*dwfUqd7ulHI724rTyyhhNg.png" /></figure><p>This is one of the reasons dense layers are sometimes called <strong>fully connected layers</strong>.</p><p>Using only dense layers, we can build surprisingly powerful neural networks that perform well on many machine learning tasks.</p><p>However, dense layers aren’t the only type of layer available.</p><p>Depending on the problem we’re trying to solve, there are other layer types that can often perform much better.</p><p>One of the most important of these is the <strong>Convolutional layer</strong>.</p><h3>Convolutional Layers</h3><p>Let’s go back to our handwritten digit recognition example.</p><p>Suppose our input <strong>x</strong> is an image of the handwritten digit <strong>5</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*TNgWNSFQYKsLn3s7aCUjsQ.png" /></figure><p>Earlier, when we used dense layers, every neuron in the first hidden layer could “see” <strong>every single pixel</strong> in the image.</p><p>But what if we changed that?</p><p>Suppose the first neuron is only allowed to look at the pixels inside the <strong>blue box</strong>.</p><p>The second neuron can only look at the pixels inside the <strong>pink box</strong>.</p><p>The third neuron looks at another small region of the image, and so on.</p><p>Instead of every neuron looking at the entire image, <strong>each neuron only looks at a small portion of it</strong>.</p><p>At first, this might seem strange.</p><p>Why would we deliberately prevent neurons from seeing the whole image?</p><p>Wouldn’t giving every neuron access to all the information make the network better?</p><p>Surprisingly, the answer is often <strong>no</strong>.</p><p>Restricting each neuron to a small region of the image has several important advantages.</p><p>First, it <strong>reduces the number of computations</strong>, making the neural network much faster to train.</p><p>Second, because the model has fewer parameters to learn, it often requires <strong>less training data</strong>.</p><p>Finally, it can also help reduce <strong>overfitting</strong>, allowing the model to generalize better to new images it hasn’t seen before.</p><p>A layer where each neuron looks at only a small region of the input is called a <strong>Convolutional layer</strong>.</p><h3>Convolutional Neural Networks (CNNs)</h3><p>When a neural network contains one or more convolutional layers, it is known as a <strong>Convolutional Neural Network</strong>, or <strong>CNN</strong> for short.</p><p>CNNs are widely used for image recognition, object detection, medical imaging, facial recognition, and many other computer vision tasks.</p><p>But convolutional layers aren’t limited to images.</p><p>They can also be used with <strong>time-series data</strong>, audio signals, and many other types of sequential data.</p><p>Let’s look at an example.</p><h3>A Convolutional Layer for an ECG Signal</h3><p>Instead of working with a 2D image, suppose our input is a <strong>1D ECG signal</strong>.</p><p>An ECG records the electrical activity of the heart over time and is often used to help diagnose heart conditions.</p><p>Suppose we collect <strong>100 measurements</strong>, giving us the following input:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*nwQKN7NsdOHKWOnxfnK8Jg.png" /></figure><p>Our goal is to train a neural network to determine whether this ECG signal indicates a heart condition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Efxcg7zv7743n3x5h56QWA.png" /></figure><p>Our goal is to train a neural network to determine whether this ECG signal indicates a heart condition.</p><p>If we were using a dense layer, every neuron would receive all <strong>100 input values</strong>.</p><p>But with a convolutional layer, we do something different.</p><p>To make the diagram easier to visualize, imagine rotating the ECG signal vertically.</p><p>Now each neuron only examines a <strong>small window</strong> of the signal.</p><p>For example:</p><ul><li>The first neuron looks at: x_1 to x_20</li><li>The second neuron looks at: x_11 to x_30</li><li>The third neuron looks at: x_21 to x_40​</li></ul><p>and so on until the final neuron looks at: x_81 to x_100</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PXdhK9cLPU7ckRYGN7C-eQ.png" /></figure><p>Notice that these windows <strong>overlap</strong>.</p><p>Each neuron shares some information with its neighboring neurons while still focusing on its own local region of the signal.</p><p>This allows the neural network to detect local patterns that might indicate a heart abnormality.</p><p>This first hidden layer is a <strong>convolutional layer</strong> because each neuron only processes a limited portion of the input instead of the entire signal.</p><p>In this example, the first convolutional layer contains <strong>9 neurons</strong>.</p><h3>Stacking Convolutional Layers</h3><p>Just like dense layers, convolutional layers can be stacked one after another.</p><p>Suppose the outputs from the first convolutional layer become the inputs to a second convolutional layer.</p><p>Instead of connecting every neuron to all <strong>9 activations</strong>, each neuron again looks at only a small subset.</p><p>For example:</p><ul><li>The first neuron might use:a_1^{[1]} to a_5^{[1]}</li><li>The second neuron might use:a_4^{[1]} to a_8^{[1]}</li><li>The final neuron might use: a_6^{[1]} to a_9^{[1]}</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CEAfIj3_0jL8MWiGRdAd9g.png" /></figure><p>Once again, each neuron focuses only on a <strong>small window</strong> of the previous layer’s activations instead of all of them.</p><p>This allows the network to gradually learn increasingly complex patterns by combining information from neighboring regions.</p><h3>Producing the Final Prediction</h3><p>After passing through several convolutional layers, we eventually reach the <strong>output layer</strong>.</p><p>Unlike the earlier layers, the output layer is <strong>not</strong> a convolutional layer.</p><p>Instead, it contains a <strong>single sigmoid neuron</strong> that receives the activations from the previous layer and produces the final prediction.</p><p>Since this is a <strong>binary classification problem</strong>, the sigmoid neuron outputs the probability that the patient has a diagnosable heart condition.</p><p>If the predicted probability is greater than our chosen threshold (for example, 0.5), we classify the ECG as indicating a heart condition. Otherwise, we classify it as normal.</p><h3>The Big Picture</h3><p>So far, we’ve focused on <strong>Dense layers</strong>, where every neuron connects to every neuron in the previous layer.</p><p>Convolutional layers take a different approach.</p><p>Instead of processing the entire input at once, each neuron focuses on a <strong>small local region</strong>, allowing the network to detect meaningful patterns while reducing the number of parameters it needs to learn.</p><p>This simple idea turns out to be incredibly powerful, which is why <strong>Convolutional Neural Networks (CNNs)</strong> have become the standard architecture for many image recognition and computer vision tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=599ff03c95b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[More Layers, Same Model? Why Activation Functions Change Everything]]></title>
            <link>https://medium.com/@prachipatel2597/more-layers-same-model-why-activation-functions-change-everything-43e169fb1839?source=rss-88a4b7f8f0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/43e169fb1839</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[activation-functions]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Prachi Patel]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 20:30:11 GMT</pubDate>
            <atom:updated>2026-07-15T20:30:11.497Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3GNtojxINMO5Lkhdki5lUg.png" /></figure><h3>Activation Functions</h3><p>So far, we’ve been using the <strong>sigmoid activation function</strong> throughout our neural networks — both in the hidden layers and the output layer.</p><p>The reason for this is that we started learning about neural networks by building on what we already knew about <strong>logistic regression</strong>. You can think of our earlier neural networks as taking many logistic regression units and connecting them together, layer by layer.</p><p>But here’s the interesting part:</p><blockquote><strong><em>We don’t always have to use the sigmoid function.</em></strong></blockquote><p>There are several other activation functions we can choose from, and selecting the right one can dramatically improve how well — and how quickly — our neural network learns.</p><p>Let’s understand why with an example.</p><h3>Going Back to Our Dress Prediction Example</h3><p>Remember our demand prediction example, where we wanted to predict whether a dress would become a bestseller based on factors such as <strong>awareness, affordability, and perceived quality</strong>?</p><p>Let’s focus on <strong>awareness</strong>.</p><p>At first, we might think of awareness as something binary:</p><blockquote><em>Either someone knows about the dress, or they don’t.</em></blockquote><p>In that case, we could represent awareness as either <strong>0 or 1</strong>.</p><p>But in reality, awareness isn’t always that simple.</p><p>Maybe someone has seen the dress once or twice but barely remembers it. Maybe they’ve repeatedly seen promotional ads for it on social media. Or perhaps the dress has gone completely viral, all their friends are talking about it, and they’re extremely aware of it.</p><p>So instead of thinking about awareness as just: 0 or 1</p><p>it might make more sense to think of it as a scale that can take <strong>any non-negative value</strong>, from zero to a much larger positive number.</p><p>Earlier, we used an equation like this to compute the activation of the neuron representing awareness:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*Zb0ATfqRXhmKibrMxeN5SA.png" /></figure><p>Because we were using the <strong>sigmoid activation function</strong>, the output was always restricted to a value between <strong>0 and 1</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*hqsNVZ8YuQeq89H79Ymt1A.png" /></figure><p>That works perfectly when we want to represent something like a probability.</p><p>But what if we want our activation value to be greater than 1?</p><p>What if an activation of 2, 10, or even 100 makes sense for what the neuron is trying to represent?</p><p>That’s where another activation function comes in.</p><h3>The ReLU Activation Function</h3><p>One of the most commonly used activation functions in neural networks is called <strong>ReLU</strong>, which stands for <strong>Rectified Linear Unit</strong>.</p><p>It looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*XWyfN_LCbsHrCSY1L3by0Q.png" /></figure><p>The idea behind ReLU is surprisingly simple.</p><p>If <strong>z</strong> is negative, the output is <strong>0</strong>:<strong> g(z) = 0 if z&lt;0</strong></p><p>But if <strong>z</strong> is zero or positive, the output is simply <strong>z</strong> itself: <strong>g(z) = z if z ≥ 0</strong></p><p>We can combine both of these rules into one simple equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*RXsUJrWg-1ax6vMrGI-V6A.png" /></figure><p>So, for example:</p><ul><li>If z=−5, then g(z)=0</li><li>If z=−1, then g(z)=0</li><li>If z=0, then g(z)=0</li><li>If z=3, then g(z)=3</li><li>If z=100, then g(z)=100</li></ul><p>Unlike sigmoid, which always produces an output between 0 and 1, <strong>ReLU can produce any non-negative value</strong>.</p><p>This makes it incredibly useful for many hidden layers in neural networks.</p><h3>Choosing an Activation Function</h3><p>The important thing to remember is that we actually have a choice when deciding what function to use for: g(z)</p><p>We don’t always have to use sigmoid.</p><p>In fact, different layers within the same neural network can use different activation functions depending on what we’re trying to accomplish.</p><p>Some of the most common activation functions are:</p><h3>Sigmoid</h3><p>The sigmoid function is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*NVScqCttMWoABHN6z0T0rQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*kH5K-atNvuAPlvvHLdaIhQ.png" /></figure><p>Its output always falls between <strong>0 and 1</strong>, making it especially useful when we want to represent a probability, such as in the output layer of a binary classification problem.</p><h3>ReLU</h3><p>The ReLU activation function is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*GnAeenAu4BPEInDqNz1pWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*YXE1ogxfNOtDuaiaLLxDvg.png" /></figure><p>It outputs <strong>0 for negative values of z</strong> and simply returns <strong>z </strong>for positive values.</p><p>ReLU is one of the most commonly used activation functions for the <strong>hidden layers of neural networks</strong>.</p><h3>Linear Activation</h3><p>We also have something called the <strong>linear activation function</strong>: g(z)=z</p><p>This one is a little unusual because applying the activation function doesn’t actually change anything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*OXZ4tEtnJr2uUwX1VJxyrw.png" /></figure><p>Remember that a neuron first computes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*kcHz3hp0FtRQf9a6ldqfVg.png" /></figure><p>Then we calculate : a=g(z)</p><p>But if: g(z) = z, then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*t_bwzNGBzYllkwHXifF3iA.png" /></figure><p>If we are trying to predict how the stock price will change the following day, it can be either positive or negative and in these cases we use the Linear Activation Function</p><h3>Softmax</h3><p>Another important activation function is <strong>Softmax</strong>, which we’ll explore separately.</p><p>Softmax is especially useful for <strong>multiclass classification problems</strong>, where instead of choosing between just two classes — such as 0 or 1 — we might need to choose between many possible categories.</p><p>For example, if we’re trying to recognize handwritten digits from <strong>0 through 9</strong>, Softmax can help us assign a probability to each possible digit.</p><h3>The Big Picture</h3><p>So far, we’ve mainly used sigmoid because it gave us a natural way to build on our understanding of logistic regression.</p><p>But neural networks give us much more flexibility.</p><p>We can choose different activation functions for different layers, and that choice can have a major impact on how well the network learns.</p><p>The three main activation functions to remember for now are:</p><ul><li><strong>Sigmoid:</strong> Outputs values between 0 and 1.</li><li><strong>ReLU:</strong> Outputs 0 or any positive value.</li><li><strong>Linear:</strong> Simply outputs z unchanged.</li></ul><p>And then there’s <strong>Softmax</strong>, which becomes especially important when we move beyond binary classification and start predicting multiple possible classes.</p><p>But this raises another important question:</p><blockquote><strong><em>How do we know which activation function to choose for each layer?</em></strong></blockquote><p>That’s exactly what we’ll look at next.</p><h3>Choosing the Right Activation Function</h3><p>Now that we’ve seen some of the most common activation functions, the next question is:</p><blockquote><strong><em>How do we know which one to use?</em></strong></blockquote><p>The answer depends on <strong>where in the neural network we’re using it</strong>.</p><p>We’ll first look at the <strong>output layer</strong>, where the choice is usually quite straightforward because it depends on what we’re trying to predict — our target value <strong>y</strong>.</p><p>After that, we’ll look at the <strong>hidden layers</strong>, where there’s one activation function that is usually the best place to start.</p><h3>Choosing an Activation Function for the Output Layer</h3><p>When deciding which activation function to use in the output layer, ask yourself one simple question:</p><blockquote><strong><em>What values can my target y take?</em></strong></blockquote><p>The answer will usually point us toward the most natural activation function.</p><h3>Case 1: Binary Classification → Sigmoid</h3><p>Suppose we’re working on a <strong>binary classification problem</strong>, where: y ∈{ 0,1}</p><p>For example:</p><ul><li>Is this email spam or not spam?</li><li>Is this tumor malignant or benign?</li><li>Will this customer churn or not?</li><li>Is this handwritten digit a 0 or a 1?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*M1rFz_mQY63BV0GBec87Ag.png" /></figure><p>In these cases, the <strong>sigmoid activation function</strong> is a natural choice for the output layer because its output always lies between <strong>0 and 1</strong></p><p>This allows us to interpret the output as the predicted probability that: y = 1</p><p>Just like we did with logistic regression.</p><p>So the rule is simple:</p><blockquote><strong><em>If y is either 0 or 1, use sigmoid in the output layer.</em></strong></blockquote><h3>Case 2: Regression with Positive or Negative Outputs → Linear</h3><p>Now suppose we’re solving a regression problem where the target value can be either <strong>positive or negative</strong>.</p><p>For example, imagine we’re trying to predict how much a stock price will change the following day.</p><p>The answer could be: +5, meaning the price increased, or: −3 meaning the price decreased.</p><p>In this case, we don’t want to restrict our neural network’s output to values between 0 and 1. We need it to be able to predict <strong>any positive or negative number</strong>.</p><p>That’s where the <strong>linear activation function</strong> makes sense: g(z)=z</p><p>Since the linear activation function doesn’t restrict the output, our neural network can predict values anywhere from: −∞ to +∞</p><p>So:</p><blockquote><strong><em>If y can take either positive or negative values, a linear activation function is a natural choice for the output layer.</em></strong></blockquote><h3>Case 3: Regression with Only Non-Negative Outputs → ReLU</h3><p>But what if we’re solving a regression problem where the output can never be negative?</p><p>For example, suppose we’re predicting the <strong>price of a house</strong>.</p><p>A house can’t have a price of:−$500,000</p><p>At least, unfortunately, no one is paying us half a million dollars to take their house.</p><p>In this case, we want our output to be restricted to: y≥0</p><p>The <strong>ReLU activation function</strong> can be a natural choice because: g(z) = max⁡(0,z)</p><p>This means the neural network can output <strong>0 or any positive value</strong>, but never a negative number.</p><p>So:</p><blockquote><strong><em>If y can only take non-negative values, ReLU can be used in the output layer.</em></strong></blockquote><h3>What About the Hidden Layers?</h3><p>The output layer is fairly straightforward because its activation function depends on the type of prediction we’re trying to make.</p><p>But what about the hidden layers?</p><p>For most neural networks, <strong>ReLU is a common default choice for hidden layers</strong>.</p><p>Earlier, we used sigmoid throughout our hidden layers because we were building our understanding of neural networks from logistic regression.</p><p>But in practice, ReLU is generally preferred over sigmoid for hidden layers.</p><p>Why?</p><p>There are two main reasons.</p><h3>Reason 1: ReLU Is Computationally Simpler</h3><p>Let’s compare the two functions.</p><p>The sigmoid activation function is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*h89pjNpagujEJZQrOFe9Pg.png" /></figure><p>This involves calculating an exponential, adding values, and taking a reciprocal.</p><p>ReLU, on the other hand, is simply: <strong>g(z)= max⁡(0,z)</strong></p><p>All we have to do is compare z with 0 and return whichever value is larger.</p><p>So from a computational perspective, ReLU is much simpler.</p><p>But there’s an even more important reason why ReLU is usually preferred.</p><h3>Reason 2: Sigmoid Can Slow Down Learning</h3><p>Let’s look at the shapes of the two functions.</p><p>For ReLU:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*Bg-roFbZBqVvniR5Kg24dw.png" /></figure><p>The function is completely flat when: z&lt;0</p><p>But for positive values: z&gt;0</p><p>it has a constant positive slope.</p><p>Now compare that with sigmoid:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*fCk69XVQrUAQQTBduNcDMA.png" /></figure><p>The sigmoid function becomes nearly flat in <strong>two places</strong>:</p><ul><li>When z is very negative</li><li>When z is very positive</li></ul><p>Why does this matter?</p><p>Remember that neural networks learn using <strong>gradient descent</strong> and <strong>backpropagation</strong>.</p><p>When the sigmoid function becomes very flat, its gradient becomes extremely small. As gradients are propagated backward through many layers, they can become smaller and smaller.</p><p>This is known as the <strong>vanishing gradient problem</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*KK_17ZjQoGT76QNpifuOjA.png" /></figure><p>When gradients become extremely small, the weights barely update, and learning can become very slow — especially in deep neural networks.</p><p>Now, to be precise, gradient descent minimizes the cost function: J(W,B)</p><p>not the activation function itself.</p><p>However, the activation functions are part of the chain of computations used to calculate the network’s output and, ultimately, the cost. Their derivatives therefore affect the gradients calculated during backpropagation.</p><p>Because sigmoid saturates and has very small gradients for large positive and negative inputs, it can contribute to vanishing gradients and slow down learning.</p><p>ReLU helps reduce this problem on its positive side because:</p><p><strong>g′(z)=1 when z&gt;0.</strong></p><p>This often allows gradients to flow more effectively through deep networks.</p><h3>So, Which Activation Function Should You Choose?</h3><p>Here’s a simple way to remember it.</p><p>For the <strong>output layer</strong>:</p><ul><li><strong>Binary classification, where y is 0 or 1</strong> → <strong>Sigmoid</strong></li><li><strong>Regression where y can be positive or negative</strong> → <strong>Linear</strong></li><li><strong>Regression where y can only be non-negative</strong> → <strong>ReLU</strong></li></ul><p>For the <strong>hidden layers</strong>:</p><blockquote><strong><em>ReLU is usually a good default starting point.</em></strong></blockquote><p>Of course, there are exceptions, and modern neural networks use many other activation functions depending on the architecture and problem.</p><p>But for now, this simple rule will take us surprisingly far.</p><h3>What Does This Look Like in TensorFlow?</h3><p>Earlier, we used sigmoid for all our layers.</p><p>But now we know that for a binary classification problem, we can use <strong>ReLU in the hidden layers</strong> and <strong>sigmoid only in the output layer</strong>:</p><pre>model = Sequential([<br>    Dense(units=25, activation=&#39;relu&#39;),<br>    Dense(units=15, activation=&#39;relu&#39;),<br>    Dense(units=1, activation=&#39;sigmoid&#39;)<br>])</pre><p>Notice the difference.</p><p>The first two hidden layers use:</p><pre>activation=&#39;relu&#39;</pre><p>while the final output layer uses:</p><pre>activation=&#39;sigmoid&#39;</pre><p>because we’re solving a binary classification problem and want the final output to represent a probability between 0 and 1.</p><h3>Beyond Sigmoid, ReLU, and Linear</h3><p>Sigmoid, ReLU, and linear aren’t the only activation functions available.</p><p>You may also come across functions such as:</p><ul><li><strong>Tanh</strong></li><li><strong>Leaky ReLU</strong></li><li><strong>Swish</strong></li><li><strong>GELU</strong></li></ul><p>Each has its own advantages and is useful in different situations. For many beginner neural network problems, though, understanding <strong>sigmoid, ReLU, and linear activation functions</strong> gives you a strong foundation.</p><p>But this leaves us with one important question:</p><blockquote><strong><em>Why do we need activation functions at all?</em></strong></blockquote><p>Why not simply use the linear activation function in every layer and keep things simple?</p><p>As it turns out, without non-linear activation functions, a deep neural network — no matter how many layers it has — would collapse into something much simpler.</p><p>And that’s exactly what we’ll look at next.</p><h3>Why Do We Need Activation Functions?</h3><p>We’ve now seen several different activation functions — sigmoid, ReLU, and linear — but this brings us to an important question:</p><blockquote><strong><em>Why do we need non-linear activation functions at all? Why not just use the linear activation function everywhere and keep things simple?</em></strong></blockquote><p>To understand why, let’s go back to our <strong>demand prediction example</strong>.</p><p>Imagine that we used the <strong>linear activation function</strong> for every neuron in our neural network. What would happen?</p><p>Surprisingly, no matter how many hidden layers we added, the entire neural network would behave just like a <strong>linear regression model</strong>.</p><p>And that would defeat one of the main reasons we use neural networks in the first place: their ability to learn <strong>complex, non-linear patterns</strong>.</p><p>Let’s see why.</p><h3>A Simple Neural Network with Linear Activations</h3><p>Consider a very simple neural network where the input x is just a single number.</p><p>The input passes through a hidden layer containing one neuron, producing an activation a^[1]. This activation then becomes the input to the output layer, which also contains one neuron and produces the final output a^[2], or f(x).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QGR4NlyrJLnuvg0aLWXA3Q.png" /></figure><p>So our network looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*BlYsGZ69jx8PlniIEfckkg.png" /></figure><p>Now suppose we use the linear activation function everywhere:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/145/1*uOcF5fO3L4jReJqNFLtW5g.png" /></figure><p>we would get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*ycotno3KHM0QLqDBA5RObg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*XcvahwQ5LUP0QpTVYaDfdw.png" /></figure><p>if we substitute the value of a^[1] in a^[2], we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*JUb0c5XsY_EsGQmnQ1MXaQ.png" /></figure><p>And if we multiply this we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*tt8Rc-dLjJKvxEoLf2YWKA.png" /></figure><p>Now suppose we combine the parameters and define:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*EO0GlgZjmXK7whS90IVr9w.png" /></figure><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*jMPHrdxqfeQ0QN3zOczN8A.png" /></figure><p>we get :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*Ggb7in-oecWAFVprNL8ENw.png" /></figure><p>Does that equation look familiar?</p><p>It should — because it’s simply the equation for <strong>linear regression</strong>.</p><p>So even though we created a neural network with multiple layers, the final output is still just a linear function of the original input x.</p><p>In other words:</p><blockquote><strong><em>A linear function of a linear function is still just another linear function.</em></strong></blockquote><p>That’s the key idea.</p><p>Adding more layers doesn’t help if every layer performs only a linear transformation. You could add 2 layers, 20 layers, or even 200 layers, and the entire network could still be mathematically collapsed into a single linear transformation.</p><h3>What Happens in a Deeper Neural Network?</h3><p>Now imagine we have a much deeper neural network with several hidden layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NKxDlOAFdOvtztlggOd8xw.png" /></figure><p>Suppose our network looks like this:</p><p>x⃗→a[1]→a[2]→a[3]→a[4]</p><p>If we use the <strong>linear activation function in every hidden layer and the output layer</strong>, then no matter how deep the network becomes, the final output can still be expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*ltA6-ZCu_GeoC7VVd7ukEw.png" /></figure><p>That’s still just a linear regression model.</p><p>So all those extra neurons and layers aren’t actually allowing the model to learn anything more complex than a linear relationship.</p><h3>What If We Use Sigmoid Only in the Output Layer?</h3><p>Now let’s change things slightly.</p><p>Suppose we still use linear activation functions for all the hidden layers, but this time we use a <strong>sigmoid activation function in the output layer</strong>.</p><p>Our final output would look something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*dDavXPE8S5929G2fCvl7qg.png" /></figure><p>But we’ve seen this equation before too.</p><p>It’s simply <strong>logistic regression</strong>.</p><p>So once again, despite having multiple hidden layers, our neural network isn’t gaining any additional power. It’s still equivalent to a much simpler model.</p><p>That’s why a common rule of thumb is:</p><blockquote><strong><em>Don’t use linear activation functions in hidden layers.</em></strong></blockquote><p>For many standard neural networks, <strong>ReLU is a much better default choice for hidden layers</strong> because it introduces the non-linearity that allows the network to learn more complex relationships.</p><h3>Why Non-Linearity Matters</h3><p>This is really the whole reason activation functions like ReLU are so important.</p><p>Without non-linear activation functions, stacking layers doesn’t give the neural network the ability to learn increasingly complex patterns.</p><p>With non-linearity, however, a neural network can learn much richer relationships in data — from simple curves to complicated decision boundaries and highly complex features in images, text, and other forms of data.</p><p>So the key takeaway is:</p><blockquote><strong><em>The power of a deep neural network doesn’t come from simply stacking more layers. It comes from combining those layers with non-linear activation functions.</em></strong></blockquote><p>So far, we’ve looked at neural networks for <strong>binary classification</strong>, where the output is either 0 or 1, as well as <strong>regression problems</strong>, where the output can take continuous values.</p><p>But what happens when we have more than two possible classes?</p><p>What if, instead of determining whether an image is a <strong>0 or a 1</strong>, we want to recognize any digit from <strong>0 through 9</strong>?</p><p>That’s where <strong>multiclass classification</strong> comes in — and that’s what we’ll explore next.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43e169fb1839" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Neural Network Is Wrong — and That’s Exactly How It Learns]]></title>
            <link>https://medium.com/@prachipatel2597/your-neural-network-is-wrong-and-thats-exactly-how-it-learns-d99d5aead520?source=rss-88a4b7f8f0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d99d5aead520</guid>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[forward-propagation]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Prachi Patel]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 15:07:09 GMT</pubDate>
            <atom:updated>2026-07-12T15:09:45.908Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lttnADBgctT9tcsNNaBZbw.png" /></figure><h3>Training Neural Networks</h3><p>So far, we’ve learned how a neural network takes an input, passes it through multiple layers, and eventually makes a prediction.</p><p>But there’s still one very important question:</p><blockquote><strong><em>How does the neural network actually learn?</em></strong></blockquote><p>Let’s go back to our <strong>digit recognition example</strong>, where our goal is to look at an image and determine whether the digit shown is a <strong>0 or a 1</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*FkNhn8TraqqJxXuc4LjTCQ.png" /></figure><p>If we look at the architecture of our neural network, we have:</p><ul><li>An input <strong>x</strong> containing the pixel values of the image</li><li>A first hidden layer with <strong>25 neurons</strong></li><li>A second hidden layer with <strong>15 neurons</strong></li><li>A final output layer with <strong>1 neuron</strong>, which gives us the probability of the image belonging to class 0 or 1</li></ul><p>Now imagine that we’re given a training dataset containing many examples of <strong>(x,y)</strong> where:</p><ul><li><strong>x</strong> represents the input image</li><li><strong>y</strong> represents the true label — either <strong>0 or 1</strong></li></ul><p>The question is:</p><blockquote><strong><em>How do we train the neural network to find the right values for all those weights and biases?</em></strong></blockquote><p>This is where TensorFlow makes our job much easier.</p><p>Here’s the code we can use to train our neural network</p><pre>import tensorflow as tf<br>from tensorflow.keras import Sequential<br>from tensorflow.keras.layers import Dense<br><br>model = Sequential([<br>    Dense(units=25, activation=&#39;sigmoid&#39;),<br>    Dense(units=15, activation=&#39;sigmoid&#39;),<br>    Dense(units=1, activation=&#39;sigmoid&#39;),<br>])<br>from tensorflow.keras.losses import BinaryCrossentropy<br>model.compile(loss=BinaryCrossentropy())<br>model.fit(X, Y, epochs=100)</pre><p>The first part should look familiar.</p><p>Starting from the Dense layers, we&#39;re simply telling TensorFlow to sequentially connect three layers together:</p><ul><li>The first layer has <strong>25 neurons</strong></li><li>The second layer has <strong>15 neurons</strong></li><li>The output layer has <strong>1 neuron</strong></li></ul><p>This is the same Sequential model we saw earlier.</p><p>But creating the neural network architecture is only the first step. We still need to tell TensorFlow <strong>how to measure whether the model’s predictions are good or bad</strong>.</p><p>That’s where model.compile() comes in.</p><p>When we compile the model, we specify the <strong>loss function</strong> that the neural network should try to minimize.</p><p>In our case, we use: BinaryCrossentropy()</p><p>Since we’re solving a <strong>binary classification problem</strong> — predicting either 0 or 1 — binary cross-entropy is an appropriate loss function.</p><p>You can think of the loss function as giving the neural network a score for how wrong its predictions are:</p><blockquote><strong><em>A smaller loss means better predictions. A larger loss means the model has more room to improve.</em></strong></blockquote><p>Once the model is compiled, we train it using: model.fit(X, y, epochs=100)</p><p>We’re essentially telling TensorFlow:</p><blockquote>“Here’s my input data X, here are the correct answers y, and I want you to learn the weights and biases that make your predictions as accurate as possible.”</blockquote><p>The epochs parameter tells TensorFlow how many times the model should go through the <strong>entire training dataset</strong>.</p><p>So if we write: epochs=100</p><p>the neural network will see the complete training dataset <strong>100 times</strong>, updating its parameters along the way to reduce the loss.</p><p>One important distinction here: <strong>an epoch isn’t necessarily the same as one step of gradient descent</strong>. If the training data is divided into multiple batches, the model can perform several parameter updates during a single epoch.</p><p>And that’s really the basic idea behind training a neural network in TensorFlow:</p><blockquote><strong><em>Build the network → Choose a loss function → Give it training data → Let it adjust its parameters to reduce the loss.</em></strong></blockquote><p>Of course, TensorFlow is hiding a lot of work behind these few lines of code. Under the hood, the model makes predictions, measures how wrong they are, calculates how each weight and bias contributed to the error, and updates those parameters to improve the next prediction.</p><h3>Detailed Training Steps</h3><p>Remember how we trained a <strong>logistic regression model</strong> earlier?</p><p>Well, training a neural network actually follows the same basic idea. Before we get into how TensorFlow does it, let’s quickly revisit the three main steps we used to train logistic regression.</p><h3>Step 1: Define how the model makes a prediction</h3><p>The first thing we need to do is define how our model takes an input and turns it into a prediction.</p><p>For logistic regression, we first compute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*pYSOJZBNXacu0P1pMWeJkA.png" /></figure><p>and then apply the <strong>sigmoid function</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*f2MkdTmH9WWDKi_CHqhCLA.png" /></figure><p>In Python, this would look something like:</p><pre>z = np.dot(w, x) + b<br>f_x = 1 / (1 + np.exp(-z))</pre><p>So, the first step is simply to specify the function that takes our input <strong>x </strong>uses the model parameters <strong>w</strong> and <strong>b</strong>, and gives us a prediction.</p><p>In other words:</p><blockquote><strong><em>Given an input, how does our model produce an output?</em></strong></blockquote><h3>Step 2: Define the loss and cost functions</h3><p>Once the model makes a prediction, the next question is:</p><blockquote><strong><em>How do we know whether that prediction was good or bad?</em></strong></blockquote><p>That’s where the <strong>loss function</strong> comes in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*q6ERoh5L_wFrDxZnZ4NP7g.png" /></figure><p>Suppose our logistic regression model predicts: f(x) and the actual label is y then for a single training example the loss is :</p><pre>loss = -y * np.log(f_x) - (1-y) * np.log(1-f_x)</pre><p>You can think of the loss as a measure of <strong>how wrong the model was for one training example</strong>.</p><p>If the model’s prediction is close to the correct answer, the loss will be small. If the prediction is far from the correct answer, the loss will be larger.</p><p>But usually, we don’t train a model on just one example. We might have hundreds, thousands, or even millions of training examples.</p><p>That’s where the <strong>cost function</strong> comes in.</p><p>The cost function takes the average loss across the entire training dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*mZ9lTqGtmInPQKkbje3JBg.png" /></figure><p>where <strong>m</strong> is the total number of training examples.</p><p>So, an easy way to remember the difference is:</p><blockquote><strong><em>Loss tells us how wrong the model is on one training example. Cost tells us how wrong the model is across the entire training set.</em></strong></blockquote><h3>Step 3: Minimize the cost using gradient descent</h3><p>Now we know:</p><ol><li>How the model makes predictions.</li><li>How to measure how wrong those predictions are.</li></ol><p>The final question is:</p><blockquote><strong><em>How do we actually make the model better?</em></strong></blockquote><p>The answer is <strong>gradient descent</strong>.</p><p>Our goal is to find values of <strong>w</strong> and <strong>b</strong> that make the cost function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/139/1*5jABfBFB6Qm-7fsMBpZc6g.png" /></figure><p>as small as possible.</p><p>Gradient descent does this by repeatedly updating the model’s parameters.</p><p>For the weights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*KVn1RHgywgt581UdrbFI5w.png" /></figure><p>In code it can be wriiten as : <strong>w = w — alpha * dj_dw</strong></p><p>and the bias:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*QxVMhc3PjKV7EcsjLPLdTQ.png" /></figure><p>In code it can be written as : <strong>b = b — alpha * dj_db</strong></p><p>Here, <strong>alpha α</strong> is the learning rate, which controls how large of a step we take with each update.</p><p>The basic idea is actually pretty intuitive:</p><blockquote><strong><em>Make a prediction → measure how wrong it was → adjust the parameters to reduce the error → repeat.</em></strong></blockquote><p>And that’s essentially how logistic regression learns.</p><p>The interesting part is that <strong>the same three basic steps can be used to train a neural network in TensorFlow</strong>:</p><ol><li><strong>Define the neural network architecture</strong> and how it computes predictions.</li><li><strong>Choose a loss function</strong> to measure how wrong those predictions are.</li><li><strong>Use an optimization algorithm</strong> to adjust the weights and biases and minimize the loss.</li></ol><p>A neural network may have thousands, millions, or even billions of parameters, but the fundamental idea behind training it remains surprisingly similar to the logistic regression model we’ve already seen.</p><p>And that’s what we’ll look at next: <strong>how TensorFlow takes these same three steps and handles the complicated calculations for us behind the scenes.</strong></p><h3>Mapping These Steps to TensorFlow</h3><p>Now that we’ve seen the three main steps used to train a logistic regression model, let’s see how those exact same steps translate to training a neural network in TensorFlow.</p><p>The good news is that TensorFlow handles most of the complicated calculations for us. What might require a lot of code and mathematics from scratch can often be done with just a few lines of TensorFlow code.</p><p>The three steps remain the same:</p><ol><li><strong>Specify how the model computes its output.</strong></li><li><strong>Specify the loss and cost functions.</strong></li><li><strong>Minimize the cost function to find good values for the model’s parameters.</strong></li></ol><p>Let’s look at each one in more detail.</p><h3>Step 1: Specify How to Compute the Output</h3><p>The first step is to define how the neural network takes an input <strong>x</strong> and turns it into a prediction f(x)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KYdRimydhNtDZ1k4q-ViKg.png" /></figure><p>In TensorFlow, we can do this by defining the architecture of our neural network:</p><pre>import tensorflow as tf<br>from tensorflow.keras import Sequential<br>from tensorflow.keras.layers import Dense<br><br>model = Sequential([<br>    Dense(units=25, activation=&#39;sigmoid&#39;),<br>    Dense(units=15, activation=&#39;sigmoid&#39;),<br>    Dense(units=1, activation=&#39;sigmoid&#39;),<br>])</pre><p>This small piece of code tells TensorFlow everything it needs to know to perform <strong>forward propagation</strong>.</p><p>For our handwritten digit classification example, the neural network contains:</p><ul><li><strong>25 neurons</strong> in the first hidden layer</li><li><strong>15 neurons</strong> in the second hidden layer</li><li><strong>1 neuron</strong> in the output layer</li></ul><p>We’re also using the <strong>sigmoid activation function</strong> for each layer.</p><p>So our neural network takes the original input <strong>x</strong> and passes it through the network like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*co_Mkz1vk5tmNQVIXn0YHA.png" /></figure><p>The output of the final layer, a^[3] is also the final prediction of our neural network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*JswRd9Nef-Gz4QNnPSQ6Vw.png" /></figure><p>Behind the scenes, each layer has its own weights and biases.</p><p>The first layer , second and their layers have their own weights and biases:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*DruerTpD15U0H8CC1mu5dA.png" /></figure><p>All these parameters are used during forward propagation to transform the original input <strong>x</strong> into the final prediction <strong>f(x)</strong>.</p><p>So, with just a few lines of code, we’ve completed the first step:</p><blockquote><strong><em>We’ve told TensorFlow exactly how our neural network should compute an output from a given input.</em></strong></blockquote><h3>Step 2: Specify the Loss and Cost Functions</h3><p>Now that our neural network can make predictions, we need a way to measure how good — or how bad — those predictions are.</p><p>For our handwritten digit classification problem, each image belongs to one of two classes: <strong>0 or 1</strong></p><p>Since this is a <strong>binary classification problem</strong>, we can use the same loss function we previously saw with logistic regression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*6T0baO3JkMHUqe1U3qxfDQ.png" /></figure><p>Here:</p><ul><li><strong>y</strong> is the actual target value, either 0 or 1.</li><li><strong>f(x)</strong> is the prediction made by our neural network.</li></ul><p>In TensorFlow, this loss function is called <strong>binary cross-entropy</strong>, and we can specify it when compiling our model:</p><pre>from tensorflow.keras.losses import BinaryCrossentropy<br>model.compile(<br>    loss=tf.keras.losses.BinaryCrossentropy()<br>)</pre><p>The name might sound a little intimidating, but the important word here is <strong>binary</strong>. It tells us that this loss function is designed for problems involving two classes — exactly like our problem of determining whether an image represents a <strong>0 or a 1</strong>.</p><p>The loss function measures the error for <strong>one training example</strong>. Once we’ve specified this loss, TensorFlow can aggregate the losses across the training data to obtain the objective used during training.</p><p>You can think of it this way:</p><blockquote><strong><em>Loss tells us how wrong the neural network is for an individual example, while the training objective summarizes that error across the training data.</em></strong></blockquote><p>The goal is then to find values for all the weights and biases that make this overall error as small as possible.</p><p>We can represent this cost function as: J(W,B)</p><p>Here, we’re using uppercase <strong>W</strong> and <strong>B</strong> because they collectively represent <strong>all the weights and biases across the entire neural network</strong>.</p><p>In other words:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*pIbMu1Kb4Kk2a9Nc4g3D0A.png" /></figure><p>and:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*AkYuNh4Q5mFOLZouA6KBKw.png" /></figure><p>So our goal is to minimize: J(W,B)</p><p>by finding the best possible values for all the parameters in the network.</p><h3>What If We’re Solving a Regression Problem?</h3><p>Of course, not every machine learning problem is a classification problem.</p><p>Suppose we’re trying to predict something continuous, such as:</p><ul><li>The price of a house</li><li>Tomorrow’s temperature</li><li>The expected sales of a product</li></ul><p>In that case, we wouldn’t use binary cross-entropy. Instead, we could use a loss function such as <strong>mean squared error</strong>.</p><p>In TensorFlow, we might write:</p><pre>from tensorflow.keras.losses import MeanSquaredError<br>model.compile(<br>    loss=tf.keras.losses.MeanSquaredError()<br>)</pre><p>The idea remains exactly the same.</p><p>We simply choose a loss function that makes sense for the problem we’re trying to solve, and TensorFlow uses that loss during training to determine how well the model is performing.</p><h3>Step 3: Minimize the Cost Function</h3><p>At this point, we’ve done two things:</p><ul><li>Defined how the neural network makes predictions.</li><li>Defined how to measure how wrong those predictions are.</li></ul><p>Now comes the most important question:</p><blockquote><strong><em>How does the neural network actually improve?</em></strong></blockquote><p>The answer is by repeatedly adjusting its weights and biases to reduce the cost function.</p><p>If we’re using gradient descent, then for every layer l and every neuron j, the weights are updated using an equation like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*URMkbsODf52S3dXYUfJyDg.png" /></figure><p>Here, <strong>alpha α</strong> is the learning rate, which determines how large of a step we take during each update.</p><p>After many iterations, the hope is that the weights and biases gradually move toward values that produce better predictions and a smaller cost.</p><p>But there’s one big question:</p><blockquote><strong><em>How do we calculate all those partial derivatives for every weight and bias in a neural network?</em></strong></blockquote><p>For a large neural network, there could be thousands, millions, or even billions of parameters. Calculating every derivative manually would obviously be impractical.</p><p>That’s where <strong>back propagation</strong> comes in.</p><p>TensorFlow uses automatic differentiation and backpropagation to efficiently calculate how each parameter contributed to the error. Those gradients are then used by an optimizer to update the parameters and reduce the loss.</p><p>And the amazing part is that when we write something as simple as:</p><pre>model.fit(X, y, epochs=100)</pre><p>TensorFlow handles the entire training process for us.</p><p>Behind that one function call, TensorFlow repeatedly:</p><ul><li>Performs <strong>forward propagation</strong> to make predictions.</li><li>Computes the <strong>loss</strong> by comparing those predictions with the actual labels.</li><li>Uses <strong>back propagation</strong> to calculate the gradients.</li><li>Uses the configured <strong>optimizer</strong> to update the weights and biases.</li><li>Repeats the process over the training data for the specified number of epochs.</li></ul><p>That’s a lot of work hidden behind one simple line of code.</p><h3>Putting It All Together</h3><p>So, when we train a neural network in TensorFlow, we’re still following the same basic three-step process we used for logistic regression:</p><blockquote><strong><em>Make a prediction → Measure how wrong it is → Adjust the parameters to improve it.</em></strong></blockquote><p>Or, in more technical terms:</p><blockquote><strong><em>Forward propagation → Compute the loss → Back propagation and parameter updates</em></strong></blockquote><p>Libraries like TensorFlow make this process incredibly convenient. In real-world machine learning projects, we’ll usually rely heavily on these libraries rather than implementing every calculation from scratch.</p><p>But understanding what’s happening underneath those few lines of code is still incredibly valuable.</p><p>Because when a model isn’t learning, the loss isn’t decreasing, or the predictions don’t make sense, knowing what TensorFlow is actually doing behind the scenes gives us a much better chance of understanding <strong>why something went wrong — and how to fix it</strong>.</p><h3><strong>Where Do We Go From Here?</strong></h3><p>And that’s how a neural network learns: it makes a prediction, measures how wrong it was using a loss function, and adjusts its parameters to improve.</p><p>TensorFlow makes this process look simple with just a few lines of code, but understanding what’s happening behind the scenes is what helps us truly understand how neural networks work.</p><p>Next, we’ll look at another important piece of the puzzle: <strong>activation functions</strong>. We’ve used sigmoid throughout our examples, but why do we need activation functions at all, and what happens when we choose a different one? That’s what we’ll explore next.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d99d5aead520" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Doing Forward Propagation by Hand: Let TensorFlow Do the Work]]></title>
            <link>https://medium.com/@prachipatel2597/stop-doing-forward-propagation-by-hand-let-tensorflow-do-the-work-2cd509377116?source=rss-88a4b7f8f0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cd509377116</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Prachi Patel]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 21:19:34 GMT</pubDate>
            <atom:updated>2026-07-20T20:43:34.066Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*z1Z4QZ9Wo6rDOhvgQaFRHg.png" /></figure><p>So far, we’ve been building neural networks by understanding what happens inside each neuron and each layer. But in practice, we don’t usually build everything from scratch.</p><p>Instead, we use deep learning libraries like <strong>TensorFlow</strong>, which handle most of the heavy lifting for us.</p><p>Let’s understand how TensorFlow works using a simple example.</p><h3>A Coffee Roasting Example ☕</h3><p>Imagine you’re running a coffee roasting business.</p><p>One question you might have is:</p><blockquote><strong><em>Can a machine learning algorithm figure out the perfect way to roast coffee beans?</em></strong></blockquote><p>To keep things simple, let’s assume that only <strong>two factors</strong> determine whether a batch of coffee turns out good or bad:</p><ul><li><strong>Roasting temperature</strong></li><li><strong>Roasting time (duration)</strong></li></ul><p>The figure below shows a simplified version of this problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bhgFC2-c2yodJPBtMplwQ.png" /></figure><p>Each <strong>X</strong> represents a batch of <strong>good coffee</strong>, while each <strong>O</strong> represents a batch of <strong>bad coffee</strong>.</p><p>If the beans are roasted for <strong>too little time</strong>, they’ll be undercooked.</p><p>Similarly, even if they’re roasted for the right amount of time, using a <strong>very low temperature</strong> can still produce poor coffee.</p><p>On the other hand, roasting the beans for <strong>too long at a very high temperature</strong> causes them to burn, giving us overcooked coffee.</p><p>Of course, real coffee roasting is much more complicated than this. There are many other factors involved. But this simplified example helps us understand how a neural network learns to make decisions.</p><h3>Representing the Input</h3><p>Suppose we want to know whether roasting coffee at <strong>400°C for 30 minutes</strong> will produce good coffee.</p><p>Instead of thinking about coffee, the neural network simply sees <strong>two numbers</strong>.</p><p>So we create an input vector: x=[400,30]</p><p>where:</p><ul><li><strong>400</strong> represents the roasting temperature.</li><li><strong>30</strong> represents the roasting duration.</li></ul><p>This vector becomes the input to our neural network.</p><h3>Creating Our First Hidden Layer</h3><p>Using TensorFlow, we can create the first hidden layer like this:</p><pre>x = np.array([[400.0, 30.0]])<br><br>layer_1 = Dense(units=3, activation=&#39;sigmoid&#39;)<br><br>a1 = layer_1(x)</pre><ul><li>A <strong>Dense layer</strong></li><li><strong>3 neurons (units)</strong></li><li>A <strong>sigmoid activation function</strong></li></ul><p>You can think of this layer as a function called <strong>layer_1</strong>.When we pass our input vector into this function, we compute: a1 = layer_1(x)</p><p>In other words, <strong>layer_1</strong> takes the input vector x , performs all the necessary computations, and returns the output of the first hidden layer.</p><p>Since this layer contains <strong>3 neurons</strong>, the output will contain <strong>3 activation values</strong>.</p><p>For example, suppose the output is: a1 = [0.5,0.8,0.1]</p><p>Each of these values is simply the activation produced by one of the three neurons in the hidden layer.</p><p>The important thing to notice is that <strong>TensorFlow performs all of these computations for us</strong>.</p><p>Earlier, we manually wrote equations for every neuron, calculated the weighted sum, added the bias, and applied the sigmoid function.</p><p>With TensorFlow, we simply define the layer once, pass in the input vector, and it automatically computes all the neuron outputs behind the scenes.</p><p>And that’s one of the biggest advantages of using deep learning frameworks — they let us focus on solving problems instead of worrying about every mathematical calculation happening underneath.</p><p>Now let’s move on to the <strong>second hidden layer</strong>.</p><p>Unlike the first hidden layer, this one contains <strong>just a single neuron</strong>. We create <strong>layer_2</strong> using the <strong>Dense</strong> layer type once again, but this time with <strong>1 unit</strong> and a <strong>sigmoid activation function</strong>.</p><p>Instead of taking the original input vector <strong>x</strong>, this layer takes the output of the previous layer, <strong>a₁</strong>, as its input. In TensorFlow, we compute this as:</p><pre>layer_2 = Dense(units=1, activation=&#39;sigmoid&#39;)<br><br>a2 = layer_2(a1)</pre><p>You can think of <strong>layer_2</strong> as another function that takes the three activation values produced by the first hidden layer, performs its own computation, and returns a single output.</p><p>Let’s assume that the output is: a2 = 0.7</p><p>Since this is our final output, we simply compare it to our threshold of <strong>0.5</strong>.</p><ul><li>If <strong>(a2 &gt; 0.5)</strong>, the neural network predicts that the coffee will be <strong>good</strong>.</li><li>If <strong>(a2 &lt; 0.5)</strong>, it predicts that the coffee will be <strong>bad</strong>.</li></ul><p>In our example, <strong>0.7 &gt; 0.5</strong>, so the neural network predicts that roasting the coffee at <strong>400°C for 30 minutes</strong> will result in <strong>good coffee</strong>.</p><p>The really nice thing is that this exact process isn’t limited to coffee roasting. We can use the same idea for our <strong>image recognition example</strong> as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vv9jvYBHMbHYZtP4emFAMg.png" /></figure><p>The only difference is that, instead of feeding the network two input values (temperature and roasting time), we feed it a much larger input vector containing all the <strong>pixel intensity values</strong> of an image. From there, the neural network processes the data layer by layer in exactly the same way before making its final prediction.</p><h3>Data in TensorFlow</h3><p>Before we start building neural networks with TensorFlow, there’s one small but important topic we need to understand — <strong>how data is represented</strong>.</p><p>If you’ve worked with Python before, you’ve probably come across <strong>NumPy</strong>. NumPy has been the standard library for numerical computing in Python for many years. TensorFlow came much later, so you’ll notice a few differences in how the two libraries represent data.</p><p>Let’s use our <strong>coffee roasting example</strong> to understand what this means.</p><p>Suppose we have an input <strong>X</strong> representing a coffee roast with two features:</p><ul><li>Temperature</li><li>Roasting time</li></ul><p>When we write <strong>X</strong> in TensorFlow, it might look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8nbUdaUKXFjm1f3A57vjhw.png" /></figure><p>If you look carefully, you’ll notice that <strong>X</strong> has <strong>two sets of square brackets</strong>.</p><p>Why are there two square brackets? And how do we know this represents a <strong>1 × 2 matrix</strong>?</p><p>To answer that, let’s first understand how <strong>NumPy stores vectors and matrices</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E9H9op9MxvdSSNEtb8cu8Q.png" /></figure><p>Look at the <strong>first matrix</strong>.It has <strong>2 rows</strong> and <strong>3 columns</strong>, so we call it a <strong>2 × 3 matrix</strong>.</p><p>The convention is always:</p><blockquote><strong><em>Number of rows × Number of columns</em></strong></blockquote><p>If we look at the code, the inner square brackets represent <strong>individual rows</strong>.For example:</p><pre>x = np.array([[1, 2, 3],<br>              [4, 5, 6]])</pre><ul><li><strong>[1, 2, 3]</strong> is the <strong>first row</strong></li><li><strong>[4, 5, 6]</strong> is the <strong>second row</strong></li></ul><p>The outer square brackets simply group these rows together to form the complete matrix.</p><p>So a matrix is really nothing more than a <strong>2-dimensional array of numbers</strong>.</p><p>Now let’s look at the <strong>second example</strong>.</p><pre>x = np.array([[0.1, 0.2],<br>              [-3.0, -4.0],<br>              [-0.5, -0.6],<br>              [7.0, 8.0]])</pre><p>This matrix has <strong>4 rows</strong> and <strong>2 columns</strong>, so we call it a <strong>4 × 2 matrix</strong>.</p><p>Again, every inner pair of square brackets represents one row, while the outer brackets combine all the rows into a single matrix.</p><h3>Row Vectors vs Column Vectors</h3><p>Now let’s go back to our coffee example.</p><p>Earlier, we wrote <strong>X</strong> like this: [[400,30]]</p><p>This creates a <strong>1 × 2 matrix</strong>.</p><p>Why?</p><p>Because both values are inside the <strong>same inner brackets</strong>, meaning they belong to the <strong>same row</strong>.</p><p>Since there is only <strong>one row</strong>, this is called a <strong>row vector</strong>.</p><p>Now compare it with this: [[400],[30]]</p><p>Although it contains the exact same numbers, this is completely different.</p><p>Here, each value is placed inside its <strong>own inner brackets</strong>, meaning each value belongs to a different row.</p><p>This creates a <strong>2 x 1 matrix</strong>.This is called a <strong>column vector</strong>.</p><p>So even though both examples contain the same numbers, the placement of the square brackets changes the shape of the data.</p><p>Now consider this example: x = np.array([400,30])</p><p>Notice that there is only <strong>one pair of square brackets</strong>.</p><p>This is <strong>not a matrix</strong>.</p><p>Instead, it’s simply a <strong>1-dimensional array (or 1D vector)</strong>.Unlike a matrix, a 1D vector doesn’t have rows and columns — it only has a length.</p><h3>Why Does TensorFlow Prefer Matrices?</h3><p>Up until now in this series, we’ve been representing our input features as <strong>1D vectors</strong> because they’re easier to understand.</p><p>However, TensorFlow follows a slightly different convention.</p><p>Instead of using 1D vectors, TensorFlow generally expects <strong>matrices</strong>, even when we’re working with a single training example.</p><p>You might be wondering:</p><blockquote><strong><em>Why make things more complicated?</em></strong></blockquote><p>The reason is actually performance.</p><p>TensorFlow is designed to train neural networks on <strong>thousands or even millions of examples at the same time</strong>.</p><p>Representing data as matrices allows TensorFlow to perform many computations simultaneously, making use of highly optimized hardware like <strong>GPUs</strong> and <strong>TPUs</strong>.</p><p>In other words, using matrices isn’t just a different way of writing data — it’s one of the reasons TensorFlow can train deep learning models so efficiently.</p><p>So, while a <strong>1D vector</strong> and a <strong>1 × 2 matrix</strong> may seem very similar, TensorFlow treats them differently because matrices make large-scale computation much faster.</p><p>Now let’s go back to our code and see what actually happens when TensorFlow performs <strong>forward propagation</strong> through the neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3mgKfbEwpWGQOuuwsq7SZQ.png" /></figure><p>Earlier, we computed:a1 = layer_1(x). Let’s assume the output is: a1 = [[0.5,0.8,0.1]].Since the first hidden layer contains <strong>3 neurons</strong>, the output contains <strong>3 activation values</strong>. This gives us a <strong>1 × 3 matrix</strong> — one row and three columns.</p><p>If we print <strong>a1</strong>, we’ll see something similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KI5CHfDsiOwg4v44jfcuIg.png" /></figure><p>Notice the text:</p><pre>shape=(1, 3)</pre><p>The <strong>shape</strong> simply tells us the dimensions of the data:</p><ul><li><strong>1 row</strong></li><li><strong>3 columns</strong></li></ul><p>You’ll also notice that the output begins with: tf.Tensor(…)</p><p>At first, the word <strong>Tensor</strong> might sound intimidating, but it’s actually quite simple.</p><p>A <strong>Tensor</strong> is just TensorFlow’s way of storing data so it can perform mathematical operations efficiently.</p><p>In this article, whenever you see the word <strong>Tensor</strong>, you can simply think of it as <strong>a way of representing vectors and matrices inside TensorFlow</strong>.</p><h3>Converting a Tensor to a NumPy Array</h3><p>Earlier, we saw that NumPy also has its own way of representing vectors and matrices.</p><p>If we ever want to convert a TensorFlow tensor into a NumPy array, it’s very straightforward.</p><p>We simply write: a1.numpy()</p><p>This doesn’t change the data at all.</p><p>array([[0.5,0.8,0.1]] ,dtype=float32)</p><p>It simply takes the values stored inside <strong>a1</strong> and represents them as a regular <strong>NumPy array</strong> instead of a TensorFlow tensor.</p><h3>The Output of the Second Layer</h3><p>So far, we’ve looked at the activations from the <strong>first hidden layer</strong>.</p><p>Now let’s see what the output of the <strong>second layer</strong> looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MkLqbs-6dG7MMXqwUMaYzg.png" /></figure><p>Suppose the output is: a2=[0.7]</p><p>Notice that <strong>a2</strong> contains just <strong>one value</strong> because the second layer has <strong>only one neuron</strong>.</p><p>Even though there is only a single number, TensorFlow still stores it as a <strong>1 × 1 matrix</strong> — that is, <strong>one row and one column</strong>.</p><p>If we print <strong>a2</strong>, we’ll see something like: tf.Tensor([[0.8]], …)</p><p>Again, this is simply TensorFlow showing us that the output is stored as a <strong>Tensor</strong>.</p><p>And just like before, if we want to convert it into a NumPy array, we can write: a2.numpy()</p><p>This gives us exactly the same value, but now it’s represented as a NumPy array instead of a TensorFlow tensor.</p><p>As you’ll notice throughout TensorFlow, you’ll often move back and forth between <strong>Tensors</strong> and <strong>NumPy arrays</strong>. Fortunately, converting between the two is quick and straightforward, making it easy to work with whichever format is most convenient.</p><h3>Building the Entire Neural Network with Sequential</h3><p>So far, we’ve seen one way of performing <strong>forward propagation</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWqdYFzad6lTI2dE7lXAdA.png" /></figure><p>We started by storing our input data in <strong>x</strong>, then created <strong>layer_1</strong> by specifying the number of neurons and the activation function. We passed <strong>x</strong> through <strong>layer_1</strong> to obtain <strong>a1</strong>, and then passed <strong>a1 </strong>into <strong>layer_2</strong> to obtain the final output.</p><p>Conceptually, this is exactly how a neural network works.</p><p>However, TensorFlow provides a much cleaner way of implementing both <strong>forward propagation</strong> and <strong>training</strong>.</p><p>Just like before, we first create <strong>layer_1</strong> and <strong>layer_2</strong>.</p><pre>layer_1 = Dense(units=3, activation=&quot;sigmoid&quot;)<br><br>layer_2 = Dense(units=1, activation=&quot;sigmoid&quot;)</pre><p>But now, instead of manually passing the output from one layer into the next, we let TensorFlow connect the layers together for us.</p><p>This is exactly what the <strong>Sequential</strong> function does.</p><pre>model = Sequential([layer_1, layer_2])</pre><p>You can think of Sequential as saying:</p><blockquote>“Here are all the layers of my neural network. Connect them together in the order I specify.”</blockquote><p>Once we’ve done that, TensorFlow knows that the output of <strong>layer_1</strong> automatically becomes the input to <strong>layer_2</strong>. We no longer have to manually write it.</p><h3>Training the Neural Network</h3><p>Remember our coffee roasting example? Let’s say we have the following training data.</p><p>We can store the input features <strong>X</strong> as a NumPy array.</p><pre>x = np.array([[450.0, 30.0],<br>              [300.0, 12.0],<br>              [500.0, 25.0],<br>              [150.0,  8.0]])</pre><p>Notice that this is a <strong>4 × 2 matrix</strong>.</p><p>Why?</p><p>Because we have:</p><ul><li><strong>4 training examples (rows)</strong></li><li><strong>2 input features (columns)</strong></li></ul><p>Next, we store the target values <strong>y</strong>.</p><pre>y = np.array([1, 0, 1, 0])</pre><p>Unlike <strong>X</strong>, <strong>y</strong> is simply a <strong>1-dimensional array</strong> containing four values — one target for each training example.</p><p>So our dataset consists of:</p><ul><li><strong>X</strong> → the input matrix</li><li><strong>y</strong> → the corresponding target labels</li></ul><p>Now we’re ready to train the neural network.</p><p>To do that, TensorFlow requires just two function calls:</p><pre>model.compile(...)<br>model.fit(x, y)</pre><p>We’ll talk about <strong>model.compile()</strong> in more detail later, so don&#39;t worry about what it does just yet.</p><p>The important function for now is: model.fit(x, y)</p><p>This tells TensorFlow:</p><blockquote>“Take the neural network we created using Sequential and train it using the training data <strong>X</strong> and <strong>y</strong>.&quot;</blockquote><p>TensorFlow then performs all the forward propagation, computes the errors, updates the weights, and repeats the process until the model learns from the data.</p><p>And the best part?</p><p>We don’t have to write any of that ourselves.</p><h3>Making Predictions</h3><p>Once the model has been trained, making predictions becomes incredibly simple.</p><p>Suppose we have a new coffee roasting example called: x_new</p><p>Instead of manually performing forward propagation through every layer, we simply write: model.predict(x_new)</p><p>TensorFlow automatically passes the input through every layer of the neural network and returns the final prediction.</p><p>In other words:</p><blockquote><strong><em>model.predict() performs forward propagation using the neural network that we created with </em></strong><strong><em>Sequential.</em></strong></blockquote><h3>The Way You&#39;ll Usually See It Written</h3><p>Earlier, we created <strong>layer_1</strong> and <strong>layer_2</strong> as separate variables before combining them.</p><pre>layer_1 = Dense(units=3, activation=&quot;sigmoid&quot;)<br>layer_2 = Dense(units=1, activation=&quot;sigmoid&quot;)<br><br>model = Sequential([layer_1, layer_2])</pre><p>While there’s nothing wrong with that, it isn’t the style you’ll usually see in real-world TensorFlow code.</p><p>Instead, it’s much more common to define the entire neural network directly inside the Sequential function.</p><pre>model = Sequential([<br>    Dense(units=3, activation=&quot;sigmoid&quot;),<br>    Dense(units=1, activation=&quot;sigmoid&quot;)<br>])</pre><p>Here we’re simply telling TensorFlow:</p><ul><li>Create a <strong>Dense layer</strong> with <strong>3 neurons</strong> and a <strong>sigmoid activation function</strong>.</li><li>Then create another <strong>Dense layer</strong> with <strong>1 neuron</strong> and a <strong>sigmoid activation function</strong>.</li></ul><p>There’s no need to create separate variables like <strong>layer_1</strong> and <strong>layer_2</strong> unless you specifically want to.</p><p>This approach is shorter, cleaner, and is the style you’ll see in most TensorFlow tutorials and production code.</p><h3>Applying the Same Idea to Digit Classification</h3><p>The exact same process works for our <strong>digit classification</strong> example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*4p8CRjAHwvu6pjgldSAP7A.png" /></figure><p>Instead of manually connecting every layer ourselves…</p><pre>layer_1 = Dense(units=25, activation=&quot;sigmoid&quot;)<br>layer_2 = Dense(units=15, activation=&quot;sigmoid&quot;)<br>layer_3 = Dense(units=1, activation=&quot;sigmoid&quot;)</pre><p>…we simply define each layer inside a Sequential model.</p><pre>model = Sequential([layer_1, layer_2, layer_3])<br><br>model.compile(...)<br><br>x = np.array([[0..., 245, ..., 17],<br>              [0..., 200, ..., 184]])<br><br>y = np.array([1, 0])<br><br>model.fit(x, y)<br><br>model.predict(x_new)</pre><p>Just like before, we:</p><ol><li>Store the training data in an input matrix <strong>X</strong>.</li><li>Store the labels in a <strong>1-dimensional array y</strong>.</li><li>Compile the model.</li><li>Train it using <strong>model.fit(X, y)</strong>.</li><li>Finally, use <strong>model.predict(x_new)</strong> to make predictions on new images.</li></ol><p>The only thing that changes is the architecture of the neural network. The overall workflow remains exactly the same.</p><p>One thing you’ll notice throughout deep learning is that libraries like TensorFlow make our lives much easier. They hide most of the complicated mathematics behind a few simple function calls.</p><p>And that’s exactly what we want in practice.</p><p>But there’s also a good reason to understand what’s happening underneath.</p><p>If something doesn’t work as expected, knowing <strong>how forward propagation actually works</strong> makes it much easier to debug problems, understand model behavior, and build better neural networks.</p><p>In real-world projects, you’ll almost always rely on libraries like TensorFlow — but understanding what they’re doing behind the scenes is what separates someone who can <strong>use</strong> deep learning from someone who truly <strong>understands</strong> it.</p><h3>General Implementation of Forward Propagation</h3><p>So far, we’ve relied on TensorFlow to perform forward propagation for us.</p><p>But have you ever wondered <strong>what’s actually happening behind the scenes?</strong></p><p>Let’s build our own implementation of a <strong>single dense layer</strong> to see how it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*FJPvY8QJMLDxqGAaLLsaCQ.png" /></figure><p><strong>def dense(a_in,W,b)</strong></p><p>The function above is called dense()</p><p>It takes three inputs:</p><ul><li><strong>a_in</strong> – the activations from the previous layer (or the original input <strong>x</strong> if this is the first hidden layer)</li><li><strong>W</strong> – the weight matrix for the current layer</li><li><strong>b</strong> – the bias values for the current layer</li></ul><p>Its job is simple:</p><blockquote><em>Given the activations from the previous layer and the parameters of the current layer, compute the activations for the current layer.</em></blockquote><h3>Organizing the Weights</h3><p>Suppose our first hidden layer contains <strong>3 neurons</strong>. Each neuron has its own weight vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3fvAED95Pp3HTHm2fkqaWA.png" /></figure><p>Instead of storing these weight vectors separately, we stack them together to form a single matrix:</p><pre>W = np.array([<br>    [3, -2, 8],<br>    [7,  5, -1]<br>])</pre><p>This becomes a <strong>2 × 3 matrix</strong>.</p><p>Why <strong>2 × 3</strong>?</p><p>Because:</p><ul><li>We have <strong>2 input features</strong> (temperature and roasting time).</li><li>We have <strong>3 neurons</strong>.</li></ul><p>Each <strong>column</strong> of this matrix contains the weights for one neuron:</p><ul><li>Column 1 → weights for neuron 1</li><li>Column 2 → weights for neuron 2</li><li>Column 3 → weights for neuron 3</li></ul><p>Similarly, each neuron also has its own bias value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*67-40VNP_3RHabal2eqqSg.png" /></figure><p>Instead of storing them individually, we place them into a single 1D array:</p><pre>b = np.array([-1, 1, 2])</pre><p>Now our entire layer can be represented using just two variables:</p><ul><li><strong>W</strong> → the weight matrix</li><li><strong>b</strong> → the bias vector</li></ul><h3>Understanding the Code</h3><p>Let’s walk through the code one step at a time.</p><pre>def dense(a_in, W, b):<br>    units = W.shape[1]<br>    a_out = np.zeros(units)<br>    for j in range(units):<br>        w = W[:, j]<br>        z = np.dot(w, a_in) + b[j]<br>        a_out[j] = g(z)</pre><p>The first line is:</p><pre>units = W.shape[1]</pre><p>Remember that <strong>W</strong> is a <strong>2 × 3 matrix</strong>.</p><p>The expression:</p><pre>W.shape</pre><p>returns:</p><pre>(2, 3)</pre><p>where:</p><ul><li><strong>2</strong> = number of rows</li><li><strong>3</strong> = number of columns</li></ul><p>Since <strong>each column corresponds to one neuron</strong>, the number of columns tells us how many neurons are in this layer. So:</p><pre>units = 3</pre><p>Next we create the output activation vector:</p><pre>a_out = np.zeros(units)</pre><p>This initializes an array filled with zeros.</p><p>Since we have <strong>3 neurons</strong>, we need <strong>3 activation values</strong>, so initially we get:</p><pre>a_out = [0, 0, 0]</pre><p>We’ll gradually replace each zero with the activation computed by its corresponding neuron.</p><h3>Computing Each Neuron</h3><p>Next, we loop through every neuron in the layer.</p><p>Since there are <strong>3 neurons</strong>, the loop runs three times:</p><ul><li><strong>j = 0</strong></li><li><strong>j = 1</strong></li><li><strong>j = 2</strong></li></ul><p>During each iteration, we need the weights for just <strong>one neuron</strong>.</p><p>This line does exactly that:</p><pre>w = W[:, j]</pre><p>If you’ve never seen this notation before, don’t worry.</p><p>The colon (:) simply means:</p><blockquote><strong><em>Take every row.</em></strong></blockquote><p>The <strong>j</strong> means:</p><blockquote><strong><em>Take the j-th column.</em></strong></blockquote><p>So when:</p><ul><li><strong>j = 0</strong>, we obtain the first column (weights for neuron 1).</li><li><strong>j = 1</strong>, we obtain the second column (weights for neuron 2).</li><li><strong>j = 2</strong>, we obtain the third column (weights for neuron 3).</li></ul><p>At this point, we have everything needed to compute one neuron.</p><p>We calculate:</p><pre>z = np.dot(w, a_in) + b[j]</pre><p>This should look familiar.</p><p>It’s exactly the equation we’ve been using throughout this series.</p><p>Next, we apply the sigmoid activation function:</p><pre>a_out[j] = g(z)</pre><p>where <strong>g</strong> is the sigmoid function.</p><p>The computed activation is then stored in the appropriate position inside <strong>a_out</strong>.</p><p>After the loop finishes, we’ve computed the activation for every neuron in the layer.</p><p>Finally, we simply return:</p><pre>return a_out</pre><h3>Connecting Multiple Layers</h3><p>Now that we have a function capable of computing <strong>one dense layer</strong>, building an entire neural network becomes surprisingly simple.</p><pre>def sequential(x):<br>    a1 = dense(x, W1, b1)<br>    a2 = dense(a1, W2, b2)<br>    a3 = dense(a2, W3, b3)<br>    a4 = dense(a3, W4, b4)<br>    f_x = a4<br>    return f_x</pre><p>Given an input vector <strong>x</strong>, we compute:</p><pre>a1 = dense(x, W1, b1)</pre><p>Here:</p><ul><li><strong>W₁</strong> and <strong>b₁</strong> are the parameters of the first hidden layer.</li><li>The output is <strong>a₁</strong>.</li></ul><p>Next, we feed <strong>a₁</strong> into the second layer:</p><pre>a2 = dense(a1, W2, b2)</pre><p>Now <strong>a₁</strong> becomes the input, while <strong>W₂</strong> and <strong>b₂</strong> are the parameters of the second layer.</p><p>The process continues in exactly the same way:</p><pre>a3 = dense(a2, W3, b3)</pre><p>Each layer simply takes the activations from the previous layer, performs its computation, and passes the result to the next layer.</p><p>This is forward propagation in its simplest form.</p><h3>A Small Notation Detail</h3><p>You may have noticed that we use an uppercase <strong>W</strong> instead of a lowercase <strong>w</strong>.</p><p>This follows a common convention in linear algebra:</p><ul><li><strong>Uppercase letters</strong> represent <strong>matrices</strong>.</li><li><strong>Lowercase letters</strong> represent <strong>vectors or scalars</strong>.</li></ul><p>Since <strong>W</strong> contains the weights for <strong>all neurons in a layer</strong>, it is a <strong>matrix</strong>, so we use an uppercase <strong>W</strong>.</p><h3>Why Learn This If TensorFlow Already Does It?</h3><p>At this point you might be thinking:</p><blockquote>“TensorFlow already has a Dense layer. Why should I care about writing my own?&quot;</blockquote><p>That’s a fair question.</p><p>In real-world projects, you’ll almost always use libraries like TensorFlow or PyTorch because they’re faster, cleaner, and highly optimized.</p><p>But understanding what’s happening <strong>under the hood</strong> is incredibly valuable.</p><p>If your model isn’t learning, if your predictions seem wrong, or if you need to debug a neural network, knowing what happens inside a dense layer makes it much easier to identify where things might be going wrong.</p><p>Libraries make our lives easier.</p><p>Understanding the mathematics behind them makes us better machine learning engineers.</p><p>In the next article, we’ll zoom out from the implementation details and explore a much bigger question:</p><p><strong>How do neural networks fit into the broader world of Artificial Intelligence? And are they really on the path to replacing human intelligence?</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cd509377116" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You See the Prediction — But What Happens Inside a Neural Network?]]></title>
            <link>https://medium.com/@prachipatel2597/you-see-the-prediction-but-what-happens-inside-a-neural-network-9b0abf697ba4?source=rss-88a4b7f8f0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b0abf697ba4</guid>
            <dc:creator><![CDATA[Prachi Patel]]></dc:creator>
            <pubDate>Fri, 22 May 2026 15:50:48 GMT</pubDate>
            <atom:updated>2026-07-17T19:40:05.942Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*IrEtEE2iJnC7cYmMgZewAA.png" /></figure><p>So far, we’ve talked about individual neurons, but a single neuron by itself can only do so much. To build something powerful, we need to group neurons together into <strong>layers</strong> — and then stack multiple layers to create a large neural network.</p><p>Let’s go back to our earlier example where we wanted to predict whether a dress would become a <strong>best seller or not</strong>.</p><p>Remember, we had <strong>four input features</strong>:</p><ul><li>Price</li><li>Shipping cost</li><li>Marketing</li><li>Material</li></ul><p>These inputs were fed into a <strong>hidden layer</strong> containing <strong>three neurons</strong>. Each neuron performed some computation and learned different things about the dress. The outputs from those three neurons were then passed to an <strong>output layer</strong>, which contained just <strong>one neuron</strong>.</p><p>That final neuron gave us the <strong>probability of the dress becoming a best seller</strong>.</p><p>Pretty cool, right?</p><p>Now, let’s zoom in a little and take a closer look at what’s actually happening inside that <strong>first hidden layer</strong>.</p><p>Even though we have <strong>three neurons</strong>, each neuron receives the <strong>same four input numbers</strong>. In other words, every neuron gets access to the dress information — price, shipping cost, marketing, and material — but each neuron may learn to focus on something different.</p><p>For example, one neuron might learn something related to <strong>affordability</strong>, another might learn <strong>brand awareness</strong>, and another might focus on <strong>perceived quality</strong>. They all look at the same inputs, but they learn different patterns from them.</p><p>And this idea — multiple neurons learning different things from the same data — is what makes neural networks so powerful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*PjNE3rAdmbVvGqHgFtTOWw.png" /></figure><p>Now let’s zoom in and look at what’s happening inside the <strong>first hidden layer</strong>.</p><p>If we focus on the <strong>first neuron</strong>, we can see that it has <strong>two parameters: w and b</strong>. Since this is the <strong>first neuron in the first hidden layer</strong>, we give them subscripts and call them</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/85/1*TDLXXjIAR2DqY2X0X0EjLA.png" /></figure><p>This neuron takes the input vector <strong>x</strong>, performs a calculation, and produces an <strong>activation value</strong>, which we call <strong>a1</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*nitb2UyJJnNHWx_qfltqJg.png" /></figure><p>If this feels familiar, that’s because it’s actually very similar to what we saw in <strong>logistic regression</strong>. The neuron computes a value z, applies the sigmoid activation function to it, and outputs a number between <strong>0 and 1</strong>.</p><p>Let’s say for the first neuron, this ends up giving us a value of <strong>0.6</strong>.</p><p>So:a1=0.6</p><p>Now the <strong>second neuron</strong> works in the exact same way, except it has its own parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/1*ytf_tV_p6ozP25zg77sQaw.png" /></figure><p>Since it’s neuron number 2, we use the subscript <strong>2</strong>. After doing its own computation, let’s say it outputs: a2=0.4</p><p>Similarly, the <strong>third neuron</strong> has parameters</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/97/1*av6KZKiIgZFRONkJz3ylPw.png" /></figure><p>and gives us:a3=0.5</p><p>Pretty straightforward, right?</p><p>Now here comes the important part.</p><p>The outputs from these three neurons are combined into something called an <strong>output vector</strong>, or <strong>activation vector</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/141/1*tLzRBVIHtnbURHg1-3LNvA.png" /></figure><p>This vector is then passed as the <strong>input to the next layer</strong>, which in our case is the <strong>final output layer containing just one neuron</strong>.</p><p>That neuron takes in these three numbers and performs its own computation to produce <strong>one final number</strong> — the probability of whether the dress will be a bestseller or not.</p><p>A useful thing to remember here is this:</p><blockquote><em>The number of values in the output vector is always equal to the number of neurons in that layer.</em></blockquote><p>So since our hidden layer has <strong>3 neurons</strong>, the output vector contains <strong>3 values</strong>.</p><p>If we look at the image above, we can also see how neural networks are organized into <strong>layers</strong>.</p><p>The initial input vector, denoted by vector <strong>x</strong>, is often called <strong>Layer 0</strong> (the input layer). The first hidden layer is called <strong>Layer 1</strong>, the next one is <strong>Layer 2</strong>, and so on.</p><p>To avoid confusion between layers, we use <strong>superscripts inside square brackets</strong>. These simply tell us <strong>which layer we’re talking about</strong>.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*HJ7RwfmRzB-H8MOJV3fJTQ.png" /></figure><p>At first this notation can look intimidating, but it’s really just a neat way of keeping track of what belongs to which layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*g-yi9WIFmnh0LMEtaRQ-ZA.png" /><figcaption>a</figcaption></figure><p>If we look closely at the image here, we’ll notice something important about the notation being used.</p><p>All the <strong>superscripts inside square brackets</strong> tell us <strong>which layer in the neural network we are referring to</strong>, while the <strong>subscript tells us the neuron number within that layer</strong>.</p><p>At first this might look a little confusing, but it’s actually pretty simple once you get used to it.</p><p>For example, if we see something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/1*bikNUCBhjI5t2kV91Gm95g.png" /></figure><p>this means we are talking about the <strong>second neuron</strong> (that’s what the subscript <strong>2</strong> means) in the <strong>first hidden layer</strong> (that’s what the superscript <strong>[1]</strong> means).</p><p>So you can think of it like this:</p><ul><li><strong>Superscript [1]</strong> → <em>Which layer are we in?</em></li><li><strong>Subscript 2</strong> → <em>Which neuron inside that layer?</em></li></ul><p>Similarly, the output activation vector:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/52/1*ahTDzSISj8V0RL-t_XH_pA.png" /></figure><p>also has a superscript of <strong>[1]</strong>, which tells us that these are the <strong>activation values coming from the first hidden layer</strong>.</p><p>And what happens next?</p><p>This output vector becomes the <strong>input to the next layer (Layer 2)</strong>, where another neuron or set of neurons performs its own computations, just like we saw earlier.</p><p>So in a neural network, information is constantly flowing from one layer to the next — each layer learning something new from the outputs of the previous one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*2-EudOK6FIun-9BjjgqvCw.png" /></figure><p>So now we have our output vector from the first hidden layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/141/1*tLzRBVIHtnbURHg1-3LNvA.png" /></figure><p>​​This vector now becomes the <strong>input to the final output layer</strong>, which in our example contains <strong>just one neuron</strong>.</p><p>And guess what? This neuron works in <strong>exactly the same way</strong> as the neurons we saw earlier.</p><p>It takes in the input values, performs a calculation using weights and bias, and then applies the <strong>sigmoid activation function</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*fHb15_mRub6Q2y_BkEJSpA.png" /></figure><p>So really, nothing new is happening here — we’re just repeating the same process, but now using the outputs from the previous layer as inputs.</p><p>Let’s say after all the calculations, the final neuron gives us an output of:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*FnCAY_JZoqclq5ea5f321g.png" /></figure><p>What does this number mean?</p><p>This becomes the <strong>probability of the dress being a bestseller</strong>.</p><p>So in simple terms:</p><ul><li><strong>0.92</strong> → an 92<strong>% probability</strong> that the dress will be a bestseller.</li></ul><p>Now here’s one small but important detail.</p><p>Earlier, our hidden layer gave us a <strong>vector of outputs</strong> because it had <strong>multiple neurons</strong>. But in the final layer, we only have <strong>one neuron</strong>, which means the output is just <strong>one number</strong>.</p><p>Because of that, the final output is called a <strong>scalar value</strong> rather than a vector.</p><p>You’ll also notice that the output has a <strong>superscript of [2]</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/46/1*Cpz6WF144nP4ss-Nz46uCw.png" /></figure><p>This simply tells us that it comes from the <strong>second and final layer</strong> of the neural network.</p><p>And if you look closely at the diagram, you’ll notice that the weights, biases, and activations in this final layer also have the superscript <strong>[2]</strong> — because they all belong to <strong>Layer 2</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a7ch31-9hnbKJThvwFMoyg.png" /></figure><p>Once you understand this notation, reading neural network equations becomes <em>way less scary</em>.</p><p>Once we obtain the output from the <strong>final layer</strong>, we look at the predicted value, denoted by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/28/1*EQ0FKOrOrwkkOeHiEm0PKQ.png" /></figure><p>In our case, let’s say the model gives us a value of <strong>0.92</strong>.</p><p>Now the question becomes: <strong>How do we decide whether the dress is a bestseller or not?</strong></p><p>This is where we use something called a <strong>threshold value</strong>.</p><p>In our example, the threshold is <strong>0.5</strong>.</p><ul><li>If the predicted value is <strong>greater than 0.5</strong>, the model predicts <strong>1</strong>, meaning the dress is likely to be a <strong>bestseller</strong>.</li><li>If the predicted value is <strong>less than 0.5</strong>, the model predicts <strong>0</strong>, meaning the dress is <strong>not likely to be a bestseller</strong>.</li></ul><p>Since:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/1*3daUXL8L5UwgbecxkcsiNw.png" /></figure><p>and <strong>0.92 &gt; 0.5</strong>, the neural network predicts <strong>1</strong>, meaning the dress is likely to become a <strong>top seller</strong>.</p><p>You can think of the threshold as the model’s way of making a final decision — almost like saying, <em>“Am I confident enough to call this a bestseller?”</em></p><h4>Complex Neural Networks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*ef9Kno_sZYQ1thkj9jUyzw.png" /></figure><p>Now let’s look at the figure above and consider this to be a <strong>more complex neural network</strong>.</p><p>Unlike our earlier example, where we had just one hidden layer, this network is deeper and contains <strong>multiple hidden layers</strong>.</p><p>In this example, we have <strong>4 layers in total</strong> (excluding the input layer and including the output layer).</p><p>One small thing to remember here:</p><blockquote><em>When people talk about the number of layers in a neural network, they usually </em><strong><em>don’t count the input layer</em></strong><em>.</em></blockquote><p>So even though we still feed in an input vector x, we start counting from the <strong>first hidden layer</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fe75EXvmtLG4Nk9HCIiMKg.png" /></figure><p>Now let’s zoom in and focus on <strong>Layer 3</strong>, which in this case is the <strong>final hidden layer</strong> before the output layer.</p><p>If we look closely, <strong>Layer 3 receives an input vector from Layer 2</strong>. In other words, the outputs computed by Layer 2 now become the inputs for Layer 3.</p><p>This input is represented as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/43/1*OHAz0CSvwOdiP3A1nfppxg.png" /></figure><p>You can think of this as the “knowledge” learned by Layer 2 being passed forward for Layer 3 to build on.</p><p>Layer 3 contains <strong>3 neurons</strong>, and each neuron has its own parameters (weights and bias):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*2fDCKpv_dg_Zx0eeAVsU5w.png" /></figure><p>Each neuron then computes its own activation value using the sigmoid function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*hqXifgjKj_7l3PvXiLzW-w.png" /><figcaption>For neuron 1 in layer 3</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*YdOYjRFy7dxgNRt_UE9bKQ.png" /><figcaption>For neuron 2 in layer 3</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*fh8irlqiAtIJ0yXbvcImTA.png" /><figcaption>For neuron 3 in layer 3</figcaption></figure><p>At first glance, these equations may look scary — but don’t worry, they’re actually doing the <strong>exact same thing</strong> we saw earlier.</p><p>The only difference is this:</p><p>Instead of using the original input vector <strong>x</strong>, the neurons are now using the <strong>output from the previous layer</strong>.</p><p>And that’s the key idea behind deep learning:</p><blockquote><em>Each layer learns something, and then passes that information to the next layer to learn something even more complex.</em></blockquote><p>These are all sigmoid functions for their respective neurons.All these comprise of</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*GvnN4y5nkv_Iu5uoftokfw.png" /></figure><p>If we notice here within each sigmoid function the vector a is from the previous layer’s input.i.e in this case it is from layer 2 and hence we see in the sigmoid functions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*D8x9PzWhZha4vOsNqqIAmw.png" /></figure><p>Now here’s an important thing to remember.</p><p>Back in the <strong>first hidden layer</strong>, the sigmoid function still used vector <strong>x</strong> because that was our original input data.</p><p>But as we move deeper into the network, the input changes.</p><p>Instead of using vector <strong>x</strong> directly, each layer uses the <strong>activation vector from the previous layer</strong>.</p><p>So mathematically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*dc1NVbdSF21ggJkAKnZJLQ.png" /></figure><p>This is just a cleaner way of keeping the notation consistent.</p><p>In other words, we can think of the original input vector <strong>x</strong> as the activation vector of <strong>Layer 0</strong>.</p><p>And once we generalize this idea, we get a formula that works for <strong>any neuron in any layer</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*VUsegIaqGs_QRcg-4OQu6g.png" /></figure><p>Okay… I know that looks intimidating</p><p>But let’s break it down piece by piece.</p><ul><li><strong>g</strong> → the <strong>sigmoid (activation) function</strong>, because it outputs activation values</li><li><strong>vector w</strong> → the <strong>weight vector</strong> for a neuron in layer ℓ</li><li><strong>j</strong> → the <strong>neuron number</strong> within the layer</li><li><strong>ℓ</strong> → the <strong>layer number</strong></li><li><strong>a^[ℓ−1]</strong>→ the <strong>output (activation vector) from the previous layer</strong>, which becomes the input for the current layer</li><li><strong>b</strong>→ the <strong>bias parameter</strong> for neuron j in layer ℓ</li></ul><p>A quick trick to remember the notation</p><p><strong>Superscript = layer number</strong><br><strong>Subscript = neuron number</strong></p><h4>Forward Propagation</h4><p>Now let’s look at a <strong>binary classification problem</strong>, where we want a neural network to look at an image and predict whether it belongs to <strong>class 0 or class 1</strong>.</p><p>To keep things simple, let’s imagine we are working with a very tiny image — an <strong>8 × 8 image</strong>.</p><p>That means we have: 8×8=64 pixel values in total.Each pixel in the image is represented by a <strong>pixel intensity value</strong>.</p><p>In our example:</p><ul><li><strong>280</strong> represents a <strong>bright white pixel</strong></li><li><strong>0</strong> represents a <strong>black pixel</strong></li><li>Any value in between represents <strong>different shades of gray</strong></li></ul><p>So instead of the computer seeing an image the way we do, it actually sees a <strong>grid of numbers</strong>.</p><p>Pretty interesting, right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*eka54hj5QanZbablxDtacg.png" /></figure><p>The question now becomes:</p><blockquote><em>Can we train a neural network to look at these 64 numbers and predict whether the image belongs to class </em><strong><em>0 or 1</em></strong><em>?</em></blockquote><p>For this example, let’s consider a neural network with:</p><ul><li><strong>2 hidden layers</strong></li><li><strong>25 neurons in the first hidden layer</strong></li><li><strong>15 neurons in the second hidden layer</strong></li><li><strong>1 neuron in the output layer</strong>, which gives us the probability of the image being <strong>0 or 1</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*_ajZjLWd8e7u3WJl_wQTtg.png" /></figure><p>The first thing the neural network does is take the input vector x and compute vector a^[1] using the neurons in the <strong>first hidden layer</strong>.</p><p>Since this layer contains <strong>25 neurons</strong>, we will have <strong>25 separate computations happening at the same time</strong>.</p><p>Each neuron computes something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*R7aZm6jiJsrff1OLYRPnIg.png" /></figure><p>Layer 1 has 25 neurons that’s why the values of w and b go from 1 to 25. Instead of the input vector x we could also have written</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/49/1*xcesdt00C7jogAyhslH3JA.png" /></figure><p>Now the second hidden layer takes the output of the first layer as input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*I9KOGAd9aq5JdJrrktD49Q.png" /></figure><p>Since this layer has <strong>15 neurons</strong>, the values of <strong>w</strong> and <strong>b</strong> now go from <strong>1 to 15</strong>.Again, every neuron learns something slightly different from the outputs of the previous layer.</p><p>The final step now is to compute the output layer which is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*Lfd2fEzpqVb_w6XpaKG0sw.png" /></figure><p>Since this layer has <strong>only one neuron</strong>, we only need <strong>one equation </strong>and w and b are also single values with :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/43/1*OHAz0CSvwOdiP3A1nfppxg.png" /></figure><p>as the input. We can check the output of :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/40/1*s08OaDUNdKie18oOci3tRw.png" /></figure><p>This gives us a single number between <strong>0 and 1</strong>.</p><p>For example:</p><ul><li><strong>0.92</strong> → high probability of class 1</li><li><strong>0.12</strong> → low probability of class 1</li></ul><p>Just like earlier, we compare this output to a <strong>threshold of 0.5</strong> to<strong> </strong>determine the final probability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*OoEUw_ffgMvfjmGNCTlw1w.png" /></figure><p>We can denote the output a^[3] as f(x).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*PKnfRElRf9K1gn8DYfS3Kw.png" /></figure><p>And since information moves <strong>from left to right</strong>, starting from the input and moving layer by layer toward the final prediction, this whole process is called:F<strong>orward Propagation.</strong></p><h3>Final Thoughts</h3><p>And there you have it — your first real look inside how <strong>neural networks actually work</strong>.</p><p>At first glance, neural networks can feel intimidating. You see strange notation, multiple layers, vectors, activation functions, and equations everywhere, and it’s easy to think:</p><blockquote>“There’s no way I’m ever going to understand this.”</blockquote><p>But if you step back, the core idea is actually pretty simple.</p><p>A neural network is really just a system of <strong>connected neurons that learn patterns from data</strong>.</p><p>Just like the human brain passes signals from one neuron to another, artificial neural networks pass information from one layer to the next. Each layer learns something slightly more meaningful than the previous one.</p><p>So far, we’ve mainly focused on <strong>how neural networks make predictions</strong>. But much bigger questions still remain:How does the network know whether its prediction was good or bad? And more importantly, how does it improve over time?</p><p>That’s where things get really interesting.</p><p>But for now, if you understand this one key idea:</p><blockquote><strong><em>A neural network is just layers of neurons learning increasingly complex patterns from data</em></strong></blockquote><p>…then you’re already much further ahead than you probably think.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b0abf697ba4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Data to Decisions: A Look Inside Neural Networks Work]]></title>
            <link>https://medium.com/@prachipatel2597/from-data-to-decisions-a-look-inside-neural-networks-work-bb28bd82a07f?source=rss-88a4b7f8f0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb28bd82a07f</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Prachi Patel]]></dc:creator>
            <pubDate>Sat, 09 May 2026 17:35:56 GMT</pubDate>
            <atom:updated>2026-06-27T13:51:43.525Z</atom:updated>
            <content:encoded><![CDATA[<h4>A beginner-friendly guide to understanding how neural networks learn, think, and make predictions.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*26NkCj4dM6GlWb3XHJT1GQ.png" /></figure><h3>Neural Networks: Introduction</h3><p>So let’s talk about neural networks.</p><p>You’ve probably heard the term “deep learning” thrown around a lot — well, neural networks are basically what people mean when they say that.</p><p>When these were first invented, the goal was actually pretty ambitious: <strong>build software that learns and thinks like the human brain</strong>.</p><p>Now, if you think about it, the human brain is insanely powerful. It can recognize faces, understand language, make decisions — all without us even realizing it. So naturally, people thought: <em>can we build something like that?</em></p><p>That’s where neural networks came in.</p><h3>Where did we first see them?</h3><p>Some of the earliest use cases were in <strong>speech recognition</strong>.<br> Then it expanded into:</p><ul><li><strong>Images (computer vision)</strong></li><li><strong>Text (natural language processing)</strong></li></ul><p>And today? They’re pretty much everywhere.</p><p>But here’s the interesting part — <br> even though neural networks were inspired by the brain, the systems we use today don’t actually work like the brain. The inspiration was biological, but what we built is more mathematical.</p><h3>Let’s understand this with neurons</h3><p>Think of a neuron in your brain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*J_OcYqOsfzSOqBIfWq_nvw.png" /></figure><p>What does it do?</p><ul><li>It receives signals from other neurons (inputs)</li><li>It processes them</li><li>It sends out a signal (output)</li></ul><p>And that output becomes input for other neurons. This keeps going… again and again.</p><p>Now imagine thousands (actually millions) of these working together. That’s your brain.</p><h3>Now let’s simplify it</h3><p>In machine learning, we take that idea and simplify it a lot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*kO4N7VQBL4t9nLJaMnJ6Cw.png" /></figure><p>A “neuron” in a neural network is basically:</p><ul><li>Taking in some numbers (inputs)</li><li>Doing a bit of math</li><li>Giving back another number (output)</li></ul><p>That’s it.</p><p>Super simple, right?</p><h3>But one neuron isn’t enough</h3><p>Here’s where it gets interesting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*7JTvTgHLozy8-hjN363eig.png" /></figure><p>Instead of just one neuron, we connect <strong>many neurons together</strong>.</p><p>Each one:</p><ul><li>Takes inputs</li><li>Does some computation</li><li>Passes output to the next</li></ul><p>So now you have a <strong>network of neurons</strong> — hence the name <em>neural network</em>.</p><h3>Why are we even learning this now?</h3><p>This is actually a really important question.</p><p>Let’s think of it like this:</p><ul><li>On one side, you have <strong>more and more data</strong> (which is happening like crazy right now)</li><li>On the other side, you have <strong>model performance</strong></li></ul><p>With traditional machine learning models like:</p><ul><li>Linear Regression</li><li>Logistic Regression</li></ul><p>Even if you give them more data, their performance doesn’t improve that much. They kind of hit a limit.</p><p>But then researchers noticed something interesting…</p><h3>Neural networks behave differently</h3><ul><li>Small neural network + lots of data → better performance</li><li>Medium network + lots of data → even better</li><li>Large network + lots of data → keeps improving</li></ul><p>Basically, neural networks <strong>love data</strong>. The more data you give them, the better they get (for many problems).</p><h3>And this is where things changed</h3><p>Once we had:</p><ul><li><strong>Huge amounts of data (Big Data)</strong></li><li><strong>More powerful models (neural networks)</strong></li></ul><p>We started seeing breakthroughs in:</p><ul><li>Speech recognition</li><li>Image recognition</li><li>Text understanding</li></ul><h3>One more piece of the puzzle: GPUs</h3><p>Training these models requires a LOT of computation.</p><p>That’s where GPUs come in.<br>They were originally made for graphics (like gaming), but they turned out to be perfect for neural networks because they can do a lot of calculations at once.</p><h3>How Do Neural Networks Work?</h3><p>Alright, now that we have an idea of what neural networks are… let’s actually understand <strong>how they work</strong>.</p><p>Let’s take a simple example.</p><p>Imagine you’re running a fashion store and trying to figure out:<br><em>Will this dress be a top seller or not?</em></p><p>Why does this matter?<br> Because if you can predict that early, you can:</p><ul><li>Stock more of it</li><li>Plan better marketing</li><li>Make more profit</li></ul><p>Pretty useful, right?</p><h3>Let’s start simple (one input)</h3><p>Let’s say we only look at <strong>one factor: price</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*6oJtbkRK63b30R1InAA6rA.png" /></figure><p>So:</p><ul><li>Input (x) = price</li><li>Output = probability that the dress is a bestseller</li></ul><p>Now, if you’ve seen logistic regression before, this is exactly what we’re doing —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*3yt3lLjSgQq_nSgXPZ6t2g.png" /></figure><p>we pass the price through a function (sigmoid), and it gives us a probability.</p><p>Instead of calling this output <strong>f(x)</strong>, we now call it <strong>a</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*o9tSA5K0dGXXDiBx8497xA.png" /></figure><p>Why “a”?<br>Because it stands for <strong>activation</strong> — a term borrowed from neuroscience.</p><p>Think of it as: <em>how strongly this neuron is “firing” or responding</em>.</p><p>So now:</p><ul><li>Input = price</li><li>Output = <strong>a (probability of being a bestseller)</strong></li></ul><h3>Think of a neuron like a tiny computer</h3><p>Honestly, the easiest way to think about a neuron is this:</p><p>It’s a tiny little computer</p><ul><li>Takes in numbers</li><li>Does some math</li><li>Outputs another number</li></ul><p>That’s it.</p><h3>Now let’s make it more realistic</h3><p>In real life, price alone doesn’t decide if something becomes a bestseller.</p><p>Think about it — what else matters?</p><ul><li>Shipping cost</li><li>Marketing</li><li>Material</li></ul><p>So now we have <strong>multiple inputs</strong>.</p><p>But even that’s not enough…</p><p>Because what we <em>actually</em> care about are things like:</p><ul><li>Is it <strong>affordable</strong>?</li><li>Are people <strong>aware</strong> of it?</li><li>Does it feel <strong>high quality</strong>?</li></ul><p>These are not directly given in the data — but they matter a lot.</p><h3>This is where neural networks get interesting</h3><p>Instead of manually calculating these, we let the network figure them out.</p><p>So we create neurons like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*b1Ie2PRjhUyK5-AOvb-agw.png" /></figure><p>Let’s look at a more complex example where we consider different features to predict whether a dress is a bestseller or not. Let’s consider the price, shipping cost, marketing cost and the material used.But we know that there is more to the dress becoming a bestseller like how affordable is it, how aware are the users of this dress and the third is the perceived quality of the dress.</p><p>So what we are going to do is to create an artificial neuron to estimate the probability that this dress is highly affordable and affordability is mainly a function of price + shipping cost. So if we add a neuron and take in price and shipping cost as the input to determine the probability of people finding this dress affordable.</p><p>We the create a second neuron to determine if there is a high awareness of this dress which is a function of how well the dress is marketed.</p><p>Finally we create a third neuron to estimate if people consider this dress to be of high quality and that is a function of the price+material. Sometimes people tend to think that the more expensive something is it is of a higher quality hence ”perceived quality”</p><h3>First layer (hidden layer)</h3><ul><li>Neuron 1 → learns <strong>affordability</strong> (from price + shipping)</li><li>Neuron 2 → learns <strong>awareness</strong> (from marketing)</li><li>Neuron 3 → learns <strong>perceived quality</strong> (from price + material)</li></ul><p>Each of these outputs a number.</p><p>These numbers are called <strong>activations</strong></p><h3>Then what happens?</h3><p>Now we take:</p><ul><li>affordability</li><li>awareness</li><li>quality</li></ul><p>…and feed them into another neuron.</p><p>That final neuron outputs: the probability of the dress being a bestseller.</p><p>That’s your prediction.</p><h3>What did we just build?</h3><p>We created:</p><ul><li><strong>Input layer</strong> → raw features (price, shipping, etc.)</li><li><strong>Hidden layer</strong> → learned features (affordability, awareness, quality)</li><li><strong>Output layer</strong> → final prediction</li></ul><p>A layer is just:<br> a group of neurons working together</p><h3>Wait… do we manually decide all this?</h3><p>Good question — and the answer is <strong>no</strong>.</p><p>In reality:<br>Every neuron gets access to all inputs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*3lqJHRQtgFTVZoD65szkbg.png" /></figure><p>So instead of manually saying:</p><ul><li>“this neuron only uses price”</li></ul><p>We let the network <strong>learn what matters</strong>.</p><p>For example:</p><ul><li>The “affordability neuron” will <em>automatically</em> learn to focus on price + shipping</li><li>And ignore irrelevant features</li></ul><h3>Let’s simplify with vectors</h3><p>Instead of writing everything separately, we group inputs like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*WWIbvAAqbBBGhFzXwMJFGA.png" /></figure><ul><li>Input features → vector <strong>x</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/34/1*66A0iZ9zFWCpxmlWpy1qLg.png" /></figure><ul><li>Hidden layer outputs → vector <strong>a</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/37/1*tG-pSF_jhJFonBW_zS4uqA.png" /></figure><p>So:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*z4VyZ75xmuAIVKQJXPaS9A.png" /></figure><h3>Why is it called a “hidden layer”?</h3><p>Because we don’t actually see what’s happening inside.</p><p>In training data, we only have:</p><ul><li>Input (x)</li><li>Output (y)</li></ul><p>We don’t have labels like:</p><ul><li>affordability</li><li>awareness</li></ul><p>These are <strong>learned internally</strong>, so they’re “hidden”.</p><h3>Another cool way to think about neural networks</h3><p>At the end of the day:It’s still logistic regression…</p><p>BUT with a twist:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*ibMvsnYK-X7arb8Il3cb2w.png" /></figure><p>Instead of using raw features (price, shipping…),it learns <strong>better features automatically</strong>.</p><h3>This replaces manual feature engineering</h3><p>Remember when we used to create features manually?</p><p>Like:</p><ul><li>House price = function of area</li><li>And area = length × breadth</li></ul><p>We had to define the area feature ourselves. That’s called <strong>feature engineering</strong></p><p>But neural networks?</p><p>They learn these features on their own</p><p>No manual work needed.</p><h3>Let’s summarize the flow</h3><ul><li>Input layer → 4 numbers (price, shipping, marketing, material)</li><li>Hidden layer → learns 3 new features (affordability, awareness, quality)</li><li>Output layer → gives 1 number (probability of bestseller)</li></ul><h3>And it doesn’t stop here…</h3><p>So far we saw is One hidden layer</p><p>But we can stack more layers like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*FIbZ8ZZRyXYackJPEWJ_4g.png" /></figure><ul><li>Input → Hidden Layer 1 → Hidden Layer 2 → Output</li></ul><p>This is called: <strong>Multi-layer neural networks (deep learning)</strong></p><p>Each layer:</p><ul><li>Takes inputs</li><li>Creates new features</li><li>Passes them forward</li></ul><h3>One important thing to remember</h3><p>The number of activations that we get after the data passing through each hidden layer is the same as the number of neurons in the previous hidden layer from which the activations have been outputted. Which is why the last layer has 1 neuron and gives us a single output.</p><ul><li>Number of neurons = number of outputs in that layer</li><li>Final layer → usually gives 1 output (our prediction)</li></ul><p>We still however need to decide how many neurons should be in each hidden layer and how many hidden layers we want while building a neural network and that coms under the neural network architecture as this will influence the performance of the neural network.</p><h3>Final thought</h3><p>The biggest advantage of neural networks is this:You don’t have to manually decide what features matter</p><p>The network:</p><ul><li>Learns patterns</li><li>Creates features</li><li>Improves predictions</li></ul><p>All on its own.</p><h3>Image Recognition</h3><p>Alright, now let’s take everything we’ve learned and apply it to something really cool — <strong>image recognition</strong>.</p><p>Let’s say we’re building a <strong>face recognition system</strong>.</p><p>What do we want it to do?<br> Take in an image and tell us <em>who that person is</em>.</p><p>Sounds simple, but there’s a lot happening behind the scenes.</p><h3>What does an image look like to a computer?</h3><p>When you look at a picture, you see a face.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*PllUdSNxsgwO_lqynwKddw.png" /></figure><p>But a computer? It just sees numbers.</p><p>For example, imagine an image that is:</p><ul><li><strong>1000 × 1000 pixels</strong></li></ul><p>That means:1 million tiny dots (pixels)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*MHj7pas0zKqfORfC2B5MIQ.png" /></figure><p>Each pixel has a value that represents brightness:</p><ul><li>0 → black</li><li>255 → white</li><li>Anything in between → shades of gray</li></ul><p>So an image is basically a <strong>grid (matrix)</strong> of numbers.</p><h3>Turning an image into input</h3><p>Now here’s what we do:</p><p>We take all those pixel values and turn them into a <strong>vector</strong>.</p><p>So instead of a 2D grid, we now have: A long list of numbers (1 million values)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*bwGyaOxZHudQR7jn79Vtiw.png" /></figure><p>Now the problem becomes:</p><p>Can we train a neural network that takes in these million numbers…<br> …and outputs the identity of the person?</p><h3>What does the neural network look like?</h3><p>Conceptually, it’s the same thing we saw before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*IUGdaeEL3ZFPP8HxLsfNvQ.png" /></figure><ul><li>Input → image (all pixel values)</li><li>Hidden layers → process and learn features</li><li>Output → probability of the person being “Person A”, “Person B”, etc.</li></ul><p>So:<br> Image → Layer 1 → Layer 2 → Layer 3 → Output</p><h3>What do the hidden layers actually learn?</h3><p>This is the coolest part.</p><p>Let’s try to “peek inside” the network.</p><h3>First hidden layer → very simple patterns</h3><p>At the beginning, neurons are learning <strong>basic things</strong> like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*fiA7ztnG0ZpIpBHJ2QuFmA.png" /></figure><ul><li>Edges</li><li>Lines</li><li>Different orientations</li></ul><p>So one neuron might detect:</p><ul><li>Vertical edges</li><li>Another → horizontal lines</li><li>Another → diagonal edges</li></ul><p>Basically, small building blocks of the image</p><h3>Second hidden layer → combining patterns</h3><p>Now the next layer takes those edges and combines them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*_yiT4zoTNfVHztZ_OtH2PQ.png" /></figure><p>So instead of lines, it starts detecting:</p><ul><li>Parts of an eye</li><li>Parts of a nose</li><li>Edges of a mouth</li></ul><p>It’s starting to understand <em>parts of a face</em></p><h3>Third hidden layer → bigger structures</h3><p>Now things get more interesting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*9KxYxzglW4xxAk9Er4C6FQ.png" /></figure><p>This layer starts detecting:</p><ul><li>Full eyes</li><li>Nose shapes</li><li>Face outlines</li></ul><p>It’s now recognizing <strong>larger and more meaningful patterns</strong></p><h3>Final layer → identity</h3><p>Finally, all of this information is combined to answer:<em>Whose face is this?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*WkFm_VpodUY2PkDKBx4k-Q.png" /></figure><p>And it outputs probabilities like:</p><ul><li>90% → Person A</li><li>5% → Person B</li><li>5% → Person C</li></ul><h3>Here’s the crazy part</h3><p>Nobody explicitly told the network:</p><ul><li>“Look for edges first”</li><li>“Then detect eyes”</li><li>“Then detect faces”</li></ul><p>It figured all of this out <strong>on its own from data</strong></p><h3>How does it improve layer by layer?</h3><p>Think of it like zooming out:</p><ul><li>First layer → looks at tiny details (edges)</li><li>Second layer → combines them into parts</li><li>Third layer → combines parts into full objects</li></ul><p>Each layer sees a <strong>bigger picture</strong> than the previous one</p><h3>And this works for everything</h3><p>This approach isn’t just for faces.</p><p>The same idea works for:</p><ul><li>Cars 🚗</li><li>Flowers 🌸</li><li>Animals 🐶</li><li>Anything in images</li></ul><p>The network just learns different patterns depending on the data.</p><h3>Big takeaway</h3><p>So if we simplify everything:</p><ul><li>Neural networks don’t “see” images like we do</li><li>They see numbers</li><li>They learn patterns step by step</li><li>From simple → to complex</li></ul><p>And somehow…they end up recognizing faces better than we expect</p><h3>Final Thoughts</h3><p>So, what’s the big takeaway here?</p><p>At first, neural networks can feel intimidating. Terms like <em>hidden layers</em>, <em>activation functions</em>, and <em>deep learning</em> make it sound like something impossibly complex. But when you break it down, a neural network is really just a system of connected mathematical neurons learning patterns from data.</p><p>Just like our brains process information step by step, neural networks take in inputs, learn simple patterns first, combine them into more meaningful features, and gradually build an understanding of complex problems. In image recognition, this could mean learning edges first, then facial features, and eventually recognizing an entire face. In text, it might mean understanding words, then sentences, and finally meaning.</p><p>What makes neural networks especially powerful is their ability to improve with more data and larger models. Instead of us manually telling them what features to look for, they learn useful representations on their own — something that has made breakthroughs in computer vision, speech recognition, recommendation systems, and natural language processing possible.</p><p>Of course, neural networks are not magic. They still need good data, computational power, and thoughtful design. But understanding the intuition behind how they work makes the whole field feel far less mysterious.</p><p>And hopefully after reading this, neural networks feel a little less like a black box — and a little more like a system you can actually understand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb28bd82a07f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your Model Needs to Be Penalized to Work Better]]></title>
            <link>https://medium.com/@prachipatel2597/why-your-model-needs-to-be-penalized-to-work-better-0cca659d16e0?source=rss-88a4b7f8f0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cca659d16e0</guid>
            <category><![CDATA[regularized-gradient-desc]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Prachi Patel]]></dc:creator>
            <pubDate>Sat, 14 Mar 2026 21:16:35 GMT</pubDate>
            <atom:updated>2026-03-14T21:16:35.862Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*fcptKvwzwRdqXkGhe4JBQg.png" /></figure><p>If you remember from earlier, we saw that when we fit a <strong>quadratic equation</strong> through this data, it gives us a pretty good fit. But when we fit a <strong>very high-degree polynomial</strong>, it ends up creating a very curvy line that <strong>overfits the data</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*MJcnOhaUmZWcTrQsq-naKA.png" /></figure><p>But now suppose we had the option of making the parameters <strong>w₃ and w₄ really small</strong>, i.e., close to 0.</p><p>What this means is that instead of minimizing the cost function for linear regression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*RKR5jKq2eU-p-Gh13DpSQQ.png" /></figure><p>we modify the equation slightly and add terms like <strong>5000w₃² and 5000w₄²</strong>.</p><p>So the new cost function becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*SpRTvpUWUkgyyAQzIvrxUA.png" /></figure><p>In this case, the cost function would get <strong>penalized if the values of w₃ and w₄ become large</strong>. Since our goal is to <strong>minimize the cost function</strong>, the only way for the algorithm to do that is by keeping <strong>w₃ and w₄ small — close to 0</strong>.</p><p>If we follow this logic and assume that <strong>w₃ and w₄ are approximately zero</strong>, then those terms effectively disappear from the model equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*igYGyj7ivhBiig262R9xzg.png" /></figure><p>And when that happens, we end up with a fit that is <strong>much closer to the quadratic function</strong>, with only <strong>tiny contributions from the x³ and x⁴ terms</strong>. This becomes similar to :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*n_giNcB_szWiWwq1-SaJeQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*xuLUw0_D27NmsBEkmx_xiw.png" /></figure><p>This gives us a much better result compared to when all parameters are large and produce a very <strong>wiggly curve</strong>.</p><h3>The Idea Behind Regularization</h3><p>The main idea behind <strong>regularization</strong> is fairly simple.</p><p>If the parameters <strong>w₁, w₂, … wₙ (and b)</strong> have <strong>smaller values</strong>, the model becomes <strong>simpler</strong> and <strong>less likely to overfit</strong>.</p><p>In our earlier example, we only penalized <strong>w₃ and w₄</strong>. But in practice, when we have many features — say <strong>100 features</strong> — we usually <strong>don’t know which ones are the most important</strong>.</p><p>Because of this, instead of penalizing just a few parameters, <strong>regularization penalizes all the parameters wⱼ</strong>.</p><p>It turns out that doing this generally results in a <strong>smoother, simpler function</strong> that is <strong>less prone to overfitting</strong>.</p><h3>Example: Many Features</h3><p>Suppose we are trying to predict the <strong>price of a house</strong> and we have <strong>100 features</strong> to choose from.</p><p>It would be very difficult to manually figure out which features to include and which ones to ignore. So instead, we build a model that <strong>includes all 100 features</strong>.</p><p>But since we don’t know which parameters are truly important, we <strong>penalize all of them slightly</strong> by adding a new term:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*IDM5mOihaXyppghCadmU-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*JdnXDc5W0T3Tx9ctDazkyw.png" /></figure><p>Here <strong>λ (lambda)</strong> is called the <strong>regularization parameter</strong> and n is the Number of features(100)</p><h3>Choosing Lambda</h3><p>Just like we choose a <strong>learning rate α</strong>, we also need to choose a value for <strong>λ</strong>.</p><p>Instead of simply using <strong>λwⱼ²</strong>, we divide λ by <strong>2m</strong>. This is done so that the <strong>same scaling factor (1/2m)</strong> appears in both parts of the cost function.</p><p>Doing this has a practical advantage:Even if our <strong>training dataset becomes larger</strong>, the <strong>same value of λ will continue to work well</strong>.</p><p>Also, in most implementations we <strong>do not penalize the parameter b</strong>, because penalizing it usually <strong>does not make much difference</strong>.</p><h3>The New Cost Function</h3><p>So now our new cost function becomes the <strong>original mean squared error term plus the regularization term</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*n44vk5YVnp-4m3PrXjBODQ.png" /><figcaption>Left part → <strong>mean squared error, </strong>Right part → <strong>regularization term</strong></figcaption></figure><p>This updated cost function helps us achieve <strong>two goals at the same time</strong>:</p><ol><li><strong>Minimize the mean squared error</strong>, so the model fits the training data well.</li><li><strong>Keep the parameters small</strong>, which helps reduce overfitting.</li></ol><p>The value of <strong>λ controls the trade-off between these two goals</strong>.</p><h3>What Happens for Different Values of Lambda?</h3><p>Let’s go back to our <strong>house price example</strong>, where f(x) is the linear regression model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*_Npna5k85ehLaPPjlpPh8w.png" /></figure><h3>Case 1 : λ = 0</h3><p>If <strong>λ = 0</strong>, then we are <strong>not using regularization at all</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*9CgjPSWGWpAE-mJtE5p6SQ.png" /></figure><p>The regularization term becomes zero, and we are left with the <strong>original cost function</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*bgpz3obN64Lm3_oEF_xSqw.png" /></figure><p>In this case, the model may produce a <strong>very wiggly curve</strong> that <strong>overfits the data</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*XvqG8cOnfDuzbCLBnBoa4w.png" /></figure><h3>Case 2 : λ is Very Large</h3><p>Now suppose <strong>λ is extremely large</strong>, say <strong>100000</strong>.</p><p>In this case, the algorithm places a <strong>very heavy weight on</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/139/1*6v2VOxA3KYn4bAu9-Sjhrg.png" /></figure><p>To minimize the cost function, the model will push all the weights <strong>w₁, w₂, w₃, w₄ … very close to zero</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*zG-5rdzoZ7Eir-_dYPiDLg.png" /></figure><p>If that happens, the model becomes:f(x)=b</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*_E676UvM-CE1yFvvezkwsQ.png" /></figure><p>which is simply a <strong>horizontal line</strong>.</p><p>This model is <strong>too simple</strong> and ends up <strong>underfitting the data</strong>.</p><h3>Case 3 : A Balanced Value of Lambda</h3><p>So what we really want is a <strong>value of λ somewhere in between</strong>.</p><p>When λ is <strong>not too large and not too small</strong>, the algorithm can strike a balance between:</p><ul><li>fitting the training data well</li><li>keeping the parameters small</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*M5cG7OM8Y2kn25m5KD_Mxw.png" /></figure><p>In this situation, we can still fit a <strong>fourth-order polynomial</strong>, but the curve will be <strong>much smoother</strong>, like the <strong>brown curve shown above</strong>.</p><p>This gives us a model that <strong>captures the pattern in the data without overfitting</strong>.</p><h3>Gradient Descent Using Regularized Linear Regression</h3><p>Let’s start by looking at the <strong>cost function for regularized linear regression</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*PBcrQ5JL97zIo9WiaFNP4A.png" /></figure><p>The first part of this equation is the <strong>usual mean squared error cost function</strong>, and now we add an <strong>additional regularization term</strong>. Here <strong>λ (lambda)</strong> is the <strong>regularization parameter</strong>, and our goal is still the same as before — we want to <strong>find parameters w and b that minimize this regularized cost function</strong>.</p><p>Earlier, when we worked with linear regression, the cost function only contained the <strong>squared error term</strong>. To minimize that cost function we used <strong>Gradient Descent</strong>, where we repeatedly updated the parameters <strong>wⱼ and b</strong>.</p><p>The gradient descent algorithm looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*osfE3ua9-j5I7EKw19GGWQ.png" /></figure><p>Here we repeatedly update the parameters <strong>wⱼ for j = 1…n</strong>, and <strong>b is updated similarly</strong>. The learning rate <strong>α (alpha)</strong> is a small number that controls how big each step of gradient descent is.</p><p>Now when we move to <strong>regularized linear regression</strong>, the algorithm is almost the same — the only difference is that the <strong>definition of the cost function J has changed slightly</strong>.</p><p>Earlier, the derivative of <strong>J with respect to wⱼ</strong> was given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*hfb_F280iWYYgbUr4XLj5w.png" /></figure><p>And the derivative with respect to <strong>b</strong> was given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*gTyGmMeV1VvEilFzpSBdUQ.png" /></figure><p>But now that we have added the <strong>regularization term</strong>, something slightly changes.</p><p>Because of the extra regularization term in the cost function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*anA_bnvB_C7b-gq3gQGbCA.png" /></figure><p>the derivative with respect to <strong>wⱼ</strong> will now include <strong>an additional term</strong>.</p><p>So the new derivative becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*OXeo9bqqBA5Fqr2Rkj69Fw.png" /></figure><p>And now the <strong>gradient descent updates for regularized linear regression</strong> become:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*OXeo9bqqBA5Fqr2Rkj69Fw.png" /><figcaption>Regularized gradient descent wrt wj</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*L-TcO-fZsjDJuuhpPMqKww.png" /><figcaption>gradient descent wrt b</figcaption></figure><p>One important thing to notice here is that <strong>we do not regularize b</strong>. In other words, we are <strong>not trying to shrink or reduce the value of b</strong>, but the regularization term does encourage the algorithm to <strong>shrink the values of wⱼ</strong>.</p><p>Finally, if we substitute these new derivatives back into our <strong>original gradient descent formula</strong>, we obtain the <strong>gradient descent algorithm for regularized linear regression</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*7fNLwZM17WKaeB4I19j6uA.png" /></figure><h3>Gradient Descent Using Regularized Logistic Regression</h3><p>Now let’s look at <strong>regularization in logistic regression</strong>.</p><p>The idea here is very similar to what we just saw with <strong>linear regression</strong>.</p><p>Earlier, we saw that <strong>logistic regression can overfit</strong> if we include <strong>very high-degree polynomial features</strong>, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*Y3mJHhSYgxHLLzUxfPyyYQ.png" /></figure><p>When that happens, the model may produce a <strong>very complicated decision boundary</strong> that twists and turns just to correctly classify every training example. This usually happens because the model is trying to fit a <strong>high-order polynomial function</strong> inside the sigmoid function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*pYy4gJApFjB_hL4DB5eoig.png" /></figure><p>When we train logistic regression with <strong>many features — whether polynomial features or regular features — the risk of overfitting becomes higher</strong>.</p><p>The cost function for logistic regression is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*84wsmXHzyN3c5vThzJiP-A.png" /></figure><p>If we want to <strong>add regularization</strong>, we simply add the regularization term to this cost function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*xx6Sd-_evV81meoSaGkd7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WFd0Qn6wIxxplCCcqY2sOQ.png" /></figure><p>Now when we minimize this cost function with respect to <strong>w and b</strong>, the regularization term <strong>penalizes large values of w₁, w₂ … wₙ</strong>. This prevents the parameters from becoming too large.</p><p>As a result, even if we use a <strong>high-order polynomial with many parameters</strong>, the decision boundary becomes <strong>much smoother</strong> and is less likely to overfit the training data. This helps the model <strong>generalize better to new examples that were not part of the training set</strong>.</p><h3>Implementing Regularized Logistic Regression</h3><p>So the next question becomes:</p><p><strong>How do we actually minimize this cost function J(w,b) that now includes the regularization term?</strong></p><p>Just like before, the answer is <strong>Gradient Descent</strong>.</p><p>The cost function we want to minimize is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WFd0Qn6wIxxplCCcqY2sOQ.png" /></figure><p>To perform gradient descent, we use the <strong>same simultaneous update rules</strong> that we are already familiar with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*w90BZNjgZMhwLEIpgs2oEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*JnN0SMirfhtlOHhOBQR9Yw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*fgyvcjSrcF8leZfMo73S3A.png" /></figure><p>When we compute the derivatives, the derivative with respect to <strong>wⱼ</strong> again gets an <strong>additional regularization term</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*phtk6RtP2m1fFGjBxKLr6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*dV1nfAFbtSRHvg4OSe2utg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*i_ZGwYfIQU-0wZekBPHFaQ.png" /></figure><p>If you look closely, this expression looks <strong>very similar to what we saw earlier in linear regression</strong>. The only difference is that here the function <strong>f(x)</strong> is the <strong>sigmoid function</strong> used in logistic regression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*e3BvhpIi7nAZlcxoZjMqNg.png" /></figure><p>And just like before, <strong>we regularize the parameters wⱼ but not b</strong>.</p><h3>Wrapping Up: Regularization + Gradient Descent</h3><p>In this article, we saw how <strong>regularization helps control overfitting</strong> by discouraging the model from assigning very large values to its parameters. By adding a <strong>penalty term to the cost function</strong>, we guide the algorithm toward <strong>simpler models</strong> that are less likely to memorize the training data and more likely to <strong>generalize well to new examples</strong>.</p><p>We also saw how this idea fits naturally into <strong>gradient descent</strong>. The update rules remain almost the same as before — the only difference is that the derivatives now include an <strong>extra term that gently shrinks the weights</strong> during each update step. Over time, this keeps the parameters from growing too large while still allowing the model to learn meaningful patterns from the data.</p><p>What’s powerful about this approach is that it works for <strong>both linear regression and logistic regression</strong>. By simply modifying the <strong>cost function</strong>, we can use the same optimization method to train models that are <strong>more stable, less prone to overfitting, and better at making predictions on unseen data</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cca659d16e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why the Perfect Fit Is a Myth: When Models That Fit Everything Predict Nothing]]></title>
            <link>https://medium.com/@prachipatel2597/why-the-perfect-fit-is-a-myth-when-models-that-fit-everything-predict-nothing-26555c6d1690?source=rss-88a4b7f8f0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/26555c6d1690</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[overfitting]]></category>
            <category><![CDATA[easy]]></category>
            <category><![CDATA[underfitting]]></category>
            <dc:creator><![CDATA[Prachi Patel]]></dc:creator>
            <pubDate>Thu, 05 Mar 2026 22:21:33 GMT</pubDate>
            <atom:updated>2026-03-05T22:21:33.056Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*IG_WTlBIwTykbdOP3sA-Fw.png" /></figure><p>Now that we have seen both <strong>Linear Regression</strong> and <strong>Logistic Regression</strong>, let’s talk about some of the issues these models might face that can cause them to fit the data poorly. Two of the most common problems are <strong>underfitting</strong> and <strong>overfitting</strong>.</p><p>Let’s start with an example of predicting <strong>house prices</strong> where we want to predict the price as a function of the <strong>size of the house</strong>, and in this case we are using <strong>linear regression</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*pwrwK0jfi-W2fB7fqeKikQ.png" /></figure><p>Over here we can see that <strong>x determines the size of the house</strong> and <strong>y is what we are trying to predict — the price</strong>. If we fit a linear regression line through the data, we get the figure shown above.</p><p>This is <strong>not a very good model</strong>. If we look at the data closely, we can see that as the <strong>size of the house increases, the price starts to flatten out</strong>. But our linear regression model forces a straight line through the data.</p><p>Because of this, the algorithm does not fit the training data very well. This situation is called <strong>underfitting</strong>, or we say the algorithm has <strong>high bias</strong>.</p><p>High bias means the algorithm has a <strong>preconceived assumption about the data</strong> that is too simple to capture the true pattern. In this case, the model assumes that the <strong>price must be a perfectly linear function of size</strong>, while the actual data clearly tells a slightly different story. Because of this rigid assumption, the model ends up fitting the data poorly.</p><p>Now let’s look at another example where we try fitting a <strong>quadratic model</strong> instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*6eVeRkUnY-CMih4ucsbApQ.png" /></figure><p>Here we introduce two features: <strong>x and x²</strong>. When we fit the parameters <strong>w₁ and w₂</strong>, we get a curve that follows the data much more closely.</p><p>Now imagine we introduce a <strong>new house that was not part of the training dataset</strong>. If the model predicts the price of this new house reasonably well, then we say that the model <strong>generalizes well</strong>.</p><p>In machine learning, <strong>Generalization</strong> refers to the model’s ability to make <strong>accurate predictions on brand-new data that it has never seen before</strong>.</p><p>This is exactly what we want our models to do — not just memorize the training data, but <strong>perform well on new unseen examples</strong>.</p><p>Now let’s look at the other extreme.</p><p>Suppose we try to fit a <strong>4th or 5th degree polynomial</strong> to the data using features like: x, x², x³, x⁴, x⁵</p><p>With enough flexibility, we can create a curve that <strong>passes through every single training point perfectly</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*k0_HI_Y9r8lwVMh-FSUhHg.png" /></figure><p>At first glance this might seem great. In fact, we could choose parameters such that the <strong>cost function J becomes exactly 0</strong>, because the prediction error on every training example is zero.</p><p>But if we look at the curve more carefully, we notice something strange — it becomes <strong>very wiggly</strong>.</p><p>For example, look at the region between <strong>data points 3 and 4</strong>. If we were to place a new data point somewhere in that dip, the model might predict a <strong>much lower price</strong> than nearby houses, even though the house size is larger.</p><p>This means the model is <strong>not reliable for predicting new data</strong>.</p><p>This situation is called <strong>overfitting</strong>.</p><p>The model fits the training data <strong>too well</strong>, capturing not just the true pattern but also the <strong>noise in the data</strong>. Because of this, it does <strong>not generalize well to new examples</strong>.</p><p>Overfitting is also associated with <strong>high variance</strong>.</p><p>High variance means the model is <strong>extremely sensitive to small changes in the training data</strong>. If we trained the model on a slightly different dataset — for example if one house was priced a little higher or lower — the resulting polynomial curve might look <strong>completely different</strong>.</p><p>So if two ML engineers trained this same 5th-order polynomial model on slightly different datasets, they might end up with <strong>very different predictions</strong>.</p><p>If we compare the <strong>generalized quadratic model</strong> with this highly overfit model, the quadratic model actually gives us <strong>more reliable predictions for new houses</strong>, even though it does not perfectly fit every training point.</p><p>In machine learning, the goal is to find a model that is <strong>neither underfitting nor overfitting</strong>.</p><p>In other words, we want a model that has <strong>low bias and low variance</strong>.</p><p>A fun way to think about this is the <strong>Goldilocks and the Three Bears analogy</strong>:</p><ul><li>If the model is <strong>too simple</strong> → it <strong>underfits</strong> (too cold)</li><li>If the model is <strong>too complex</strong> → it <strong>overfits</strong> (too hot)</li><li>The best model is <strong>just right</strong> → it <strong>generalizes well</strong></li></ul><p>So far we’ve looked at <strong>overfitting and underfitting in linear regression</strong>.Let’s now see how the same idea appears in a <strong>classification problem</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*ceV781I1Z37Xubm6W8LbBA.png" /></figure><p>Consider our earlier <strong>tumor classification example</strong>, where:</p><ul><li><strong>x₁ = tumor size</strong></li><li><strong>x₂ = patient age</strong></li></ul><p>We are trying to classify whether the tumor is <strong>malignant or benign</strong>, represented by crosses and circles.</p><p>One approach is to fit a <strong>logistic regression model: </strong>f(x)=g(z)</p><p>where <strong>g</strong> is the <strong>sigmoid function</strong>, and the inner value is <strong>z</strong>.</p><p>In this case, the <strong>decision boundary occurs where z = 0</strong>, which gives us a <strong>straight line</strong> separating the positive and negative examples.</p><p>This line is <strong>not terrible</strong>, but it is also <strong>not the best fit for the data</strong>. It cannot capture the shape that separates the two groups properly.</p><p>This is another example of <strong>underfitting (high bias)</strong>.</p><p>Now suppose we add <strong>quadratic terms</strong> to our features.</p><p>Then <strong>z becomes</strong> a function containing <strong>x₁² and x₂²</strong>, and the decision boundary <strong>z = 0</strong> may look like a <strong>curved ellipse</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*I8qlkSyB_iGEnBqRjAr9Dw.png" /></figure><p>This curve fits the data <strong>much better</strong>, even though it still does not perfectly classify every training point.</p><p>You may notice that <strong>a few circles appear among the crosses</strong>, meaning a few points are misclassified. But that’s actually okay — the model still captures the <strong>overall structure of the data well</strong>.</p><p>Finally, let’s look at the other extreme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*xBvGknMbOIPPvwggWAo3Dw.png" /></figure><p>If we add <strong>many high-order polynomial features</strong> the decision boundary can become <strong>very complex</strong>, twisting and contouring itself in order to perfectly separate every training example.</p><p>While this might look impressive because it <strong>classifies the training data perfectly</strong>, it is actually <strong>not a good model for making predictions</strong>.</p><p>This is another example of <strong>overfitting and high variance</strong>.</p><p>Even though the model performs extremely well on the training set, it is <strong>unlikely to generalize well to new data</strong>, which is what ultimately matters in machine learning.</p><h3>Addressing Overfitting and Underfitting</h3><p>Let’s say we train a model and notice that it has <strong>high variance</strong>, meaning the model has <strong>overfit the training data</strong>.</p><p>One way we can address this issue is by <strong>collecting more training data</strong> — for example, gathering more examples of <strong>house sizes and their corresponding prices</strong>. With a larger training dataset, the learning algorithm can learn a function that is <strong>less wiggly and more stable</strong>.</p><p>Even if we use a <strong>higher-order polynomial model with many features</strong>, having enough training examples can help the algorithm learn a smoother function that generalizes better.</p><p>In fact, <strong>one of the best ways to overcome overfitting is to simply get more data</strong>. However, this is not always possible. For example, maybe only a limited number of houses were sold in a certain area, or perhaps the additional data is unavailable for some other reason. But when it <em>is</em> possible, collecting more data is often a great solution.</p><p>Another approach is to <strong>include only the features that actually impact the price of the house</strong>, rather than using every feature available.</p><p>For example, earlier we introduced polynomial features like:x, x², x³, …</p><p>One way to reduce overfitting is to <strong>avoid using too many polynomial terms</strong>.</p><p>But let’s look at another scenario. Suppose we have many different features available, such as:</p><ul><li>size (x₁)</li><li>number of bedrooms (x₂)</li><li>number of floors (x₃)</li><li>age of the house (x₄)</li></ul><p>and perhaps many more features that we use to predict the house price <strong>y</strong>.</p><p>If we have <strong>a large number of features but only a small amount of training data</strong>, the learning algorithm may start to <strong>overfit the training set</strong>.</p><p>In this case, instead of using all 100 features, we might choose only the <strong>most useful ones</strong>, such as size, number of bedrooms, and age. Using this smaller subset of features may result in a model that <strong>no longer overfits</strong>.</p><p>This process of selecting the most relevant features is called <strong>Feature Selection</strong>.</p><p>One way to perform feature selection is by using <strong>intuition or domain knowledge</strong> to decide which features are likely to matter most.</p><p>However, one disadvantage of feature selection is that by choosing only a few features, the algorithm may <strong>discard potentially useful information</strong>. What if all 100 features actually contribute in some way to predicting the price of the house?</p><p>Later we will see techniques that allow algorithms to <strong>automatically determine which features are most important</strong>. But for now, there is another approach we can use, called <strong>Regularization</strong>.</p><h3>Regularization</h3><p>Consider an overfit model with a <strong>very high-degree polynomial</strong>, such as:x, x², x³, x⁴, …</p><p>In such models, we often find that the <strong>parameters (weights) associated with these features become very large</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*JwxPC4gnFB46mubWu8EI1Q.png" /></figure><p>One extreme way to deal with this would be to <strong>eliminate some features entirely</strong>. For example, we could set the coefficient of x⁴ to zero. Setting a parameter to zero effectively <strong>removes that feature from the model</strong>.</p><p>Regularization takes a slightly different approach.</p><p>Instead of completely eliminating features, <strong>regularization gently reduces their influence</strong>.</p><p>In other words, regularization <strong>encourages the algorithm to shrink the values of the parameters</strong>, making them smaller so that their impact on the model is reduced — but <strong>without forcing them to be exactly zero</strong>.</p><p>So even if we have a higher-order polynomial model, the weights associated with those higher-order terms may become <strong>very small</strong>, which reduces their influence. As a result, the model becomes <strong>smoother and less prone to overfitting</strong>, while still retaining all the features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*pda6Dix0zev8LHYt5kgInA.png" /></figure><p>This allows us to <strong>keep all the available features without letting any single feature dominate the model excessively</strong>.</p><p>Sometimes we also regularize the <strong>bias parameter b</strong>, though in many implementations it is left unregularized since it usually does not have a large effect.</p><p>So far, we have discussed <strong>three main ways to address overfitting</strong>:</p><ol><li><strong>Collect more training data</strong></li></ol><ul><li>Often the most effective solution</li><li>But not always possible</li></ul><p>2.<strong> Use a smaller subset of features (Feature Selection)</strong></p><ul><li>Helps reduce overfitting</li><li>But may discard potentially useful information</li></ul><p>3.<strong> Regularization</strong></p><ul><li>Keeps all features</li><li>Reduces the size of the parameters so they have less impact</li></ul><h3>Conclusion</h3><p>In this article, we explored two very common problems that machine learning models face: <strong>underfitting and overfitting</strong>.</p><p>We saw how a model that is <strong>too simple</strong> may fail to capture the true pattern in the data, leading to <strong>underfitting (high bias)</strong>. On the other hand, a model that is <strong>too complex</strong> may try to memorize every training example, resulting in <strong>overfitting (high variance)</strong> and poor performance on new data.</p><p>Using examples from both <strong>linear regression and logistic regression</strong>, we saw how increasing the complexity of a model — for example by adding higher-order polynomial features — can sometimes help the model fit the data better, but can also make the model overly sensitive to the training data.</p><p>In the <strong>next article</strong>, we will take a deeper look at <strong>regularization</strong> and see how it changes the <strong>cost function</strong> and the <strong>gradient descent updates</strong> for both <strong>linear regression and logistic regression</strong>. This will help us understand how models can stay flexible enough to learn meaningful patterns while still avoiding overfitting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26555c6d1690" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>