保留正文与补采附件。源页面当前未重新核验;具体限制见交付清单。
We value your privacy
We use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking "Accept All", you consent to our use of cookies.
Customise Reject All Accept All
Customise Consent Preferences
We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.
The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more
NecessaryAlways Active
Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.
Cookie BCTempID
Duration 10 minutes
Description No description available.
Cookie __cf_bm
Duration 1 hour
Description This cookie, set by Cloudflare, is used to support Cloudflare Bot Management.
Cookie AWSALBCORS
Duration 7 days
Description Amazon Web Services set this cookie for load balancing.
Cookie _cfuvid
Duration session
Description Cloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services
Cookie li_gc
Duration 6 months
Description Linkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.
Cookie __hssrc
Duration session
Description This cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.
Cookie __hssc
Duration 1 hour
Description HubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.
Cookie wpEmojiSettingsSupports
Duration session
Description WordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.
Cookie BCSessionID
Duration 1 year 1 month 4 days
Description Blueconic sets this cookie as a unique identifier for the BlueConic profile.
Cookie _octo
Duration 1 year
Description No description available.
Cookie logged_in
Duration 1 year
Description No description available.
Cookie __Secure-YEC
Duration past
Description YouTube sets this cookie to stores the user's video player preferences using embedded YouTube video
Cookie __eoi
Duration 6 months
Description Description is currently not available.
Cookie AWSALBTGCORS
Duration 7 days
Description No description available.
Cookie login-status-p
Duration past
Description Description is currently not available.
Cookie AWSALBTG
Duration 7 days
Description No description available.
Cookie csrf_token
Duration session
Description No description available.
Cookie token_v2
Duration 1 day
Description Description is currently not available.
Cookie D
Duration 1 year
Description Description is currently not available.
Cookie PHPSESSID
Duration session
Description This cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.
Cookie VISITOR_PRIVACY_METADATA
Duration 6 months
Description YouTube sets this cookie to store the user's cookie consent state for the current domain.
Cookie cookietest
Duration session
Description The cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.
Cookie __Host-airtable-session
Duration 1 year
Description This cookie is used to enable us to integrate the services of Airtable.
Cookie __Host-airtable-session.sig
Duration 1 year
Description This cookie is used to enable us to integrate the services of Airtable.
Cookie m
Duration 1 year 1 month 4 days
Description Stripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.
Cookie BIGipServer*
Duration session
Description Marketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user.
Cookie __cfruid
Duration session
Description Cloudflare sets this cookie to identify trusted web traffic.
Cookie _GRECAPTCHA
Duration 6 months
Description Google Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.
Cookie __Secure-YNID
Duration 6 months
Description Google cookie used to protect user security and prevent fraud, especially during the login process.
Cookie cookieyes-consent
Duration 1 year
Description CookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.
Functional Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.
Cookie lidc
Duration 1 day
Description LinkedIn sets the lidc cookie to facilitate data center selection.
Cookie brw
Duration 1 year
Description No description available.
Cookie brwConsent
Duration 5 minutes
Description Description is currently not available.
Cookie WMF-Uniq
Duration 1 year
Description Description is currently not available.
Cookie loom_anon_comment
Duration 1 year
Description No description available.
Cookie loom_referral_video
Duration session
Description Description is currently not available.
Cookie VISITOR_INFO1_LIVE
Duration 6 months
Description A cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.
Cookie yt-remote-connected-devices
Duration Never Expires
Description YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.
Cookie ytidb::LAST_RESULT_ENTRY_KEY
Duration Never Expires
Description The cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.
Cookie yt-remote-device-id
Duration Never Expires
Description YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.
Cookie yt-remote-session-name
Duration session
Description The yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.
Cookie yt-remote-fast-check-period
Duration session
Description The yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.
Cookie yt-remote-session-app
Duration session
Description The yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.
Cookie yt-remote-cast-available
Duration session
Description The yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.
Cookie yt-remote-cast-installed
Duration session
Description The yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.
Cookie cp_session
Duration 3 months
Description Codepen sets this cookie for Help systems found in the website.
Cookie loid
Duration 1 year 1 month 4 days
Description This cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.
Analytics Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.
Cookie __hstc
Duration 6 months
Description Hubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).
Cookie hubspotutk
Duration 6 months
Description HubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.
Cookie _ga
Duration 1 year 1 month 4 days
Description Google Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.
Cookie ga*
Duration 1 year 1 month 4 days
Description Google Analytics sets this cookie to store and count page views.
Cookie __Host-psifi.analyticsTrace
Duration 6 hours
Description Description is currently not available.
Cookie __Host-psifi.analyticsTraceV2
Duration 6 hours
Description Description is currently not available.
Cookie _gh_sess
Duration session
Description GitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.
Cookie YSC
Duration session
Description YSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.
Cookie ajs_anonymous_id
Duration 1 year
Description This cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.
Cookie vuid
Duration 1 year 1 month 4 days
Description Vimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website.
Performance Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Cookie AWSALB
Duration 7 days
Description AWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.
Cookie acq
Duration past
Description Description is currently not available.
Cookie acq.sig
Duration past
Description Description is currently not available.
Cookie ptc
Duration 2 years
Description No description available.
Advertisement Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.
Cookie muc_ads
Duration 1 year 1 month 4 days
Description Twitter sets this cookie to collect user behaviour and interaction data to optimize the website.
Cookie guest_id_marketing
Duration 1 year 1 month 4 days
Description Twitter sets this cookie to identify and track the website visitor.
Cookie guest_id_ads
Duration 1 year 1 month 4 days
Description Twitter sets this cookie to identify and track the website visitor.
Cookie personalization_id
Duration 1 year 1 month 4 days
Description Twitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.
Cookie guest_id
Duration 1 year 1 month 4 days
Description Twitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.
Cookie bcookie
Duration 1 year
Description LinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.
Cookie __Secure-ROLLOUT_TOKEN
Duration 6 months
Description YouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.
Cookie yt.innertube::nextId
Duration Never Expires
Description YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.
Cookie yt.innertube::requests
Duration Never Expires
Description YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.
Cookie session_tracker
Duration session
Description This cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.
Cookie edgebucket
Duration session
Description Reddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.
Cookie did
Duration 1 year
Description Arbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.
Uncategorised Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet. No cookies to display. Reject All Save My Preferences Accept All Toggle SearchToggle Mobile Navigation Publish AI, ML & data-science insights to a global community of data professionals. Sign inSubmit an Article LatestEditor's PicksNewsletterShipAI
Write For TDS LinkedInXToggle Search Artificial Intelligence
Transforming Backpropagation's Complex Math into Manageable and Easy-to-Learn Bites
Amy Ma
January 17, 202420 min read
Image created by the author using ChatGPT.
Welcome back to the latest chapter of 'Courage to Learn ML. In this series, I aim to demystify complex ML topics and make them engaging through a Q&A format.
This time, our learner is exploring backpropagation and has chosen to approach it through coding. He discovered a Python tutorial on Machine Learning Mastery, which explains backpropagation from scratch using basic Python, without any deep learning frameworks. Finding the code a bit puzzling, he visited the mentor and asked for guidance to better understand both the code and the concept of backpropagation.
As always, here's a list of the topics we'll be exploring today:
Learn this step by step with the interactive AI Engineer, AI and Data Scientist and Machine Learning roadmaps.
Let's start with the fundamental why -
Gradient descent is a key optimization method in machine learning. It's not just limited to training DNNs but is also used to train models like logistic and linear regression. The fundamental idea behind it is that by minimizing the differences between predictions and true labels (prediction error), our model will get closer to the underlying true model. In gradient descent, the gradient, represented by ∇𝜃𝐽(𝜃) and formed by the loss function's partial derivatives with respect to each parameter, guides the update of parameters: 𝜃 = 𝜃 - 𝜂⋅∇𝜃𝐽(𝜃). This process is akin to dissecting a complex movement into basic movements in video games. However, in DNNs, which involve multiple layers and millions of parameters, calculating these partial derivatives for each parameter becomes computationally intensive. Particularly in a layered structure, it's crucial to distinguish the error contribution of each layer to understand how the parameters at different layers should change with respect to the overall loss. This is where Backpropagation comes in. It is a method to efficiently compute gradients for DNNs. Backpropagation assists DNNs in using gradient descent to guide their learning process, calculate the partial derivatives, and adjust each parameter more efficiently. The key to backpropagation lies in its name - it stands for 'backward propagation of errors.' This means the process involves sending the error (between the current prediction and the true label) backward and distributing the gradient from the output layer to the input layer and hidden layers in between. This distribution is in the reverse direction compared to the forward direction used to generate predictions.
This question is about the preference for deep networks over shallow ones. Before jumping into it, let's define shallow networks as having only 1 or 2 hidden layers. According to the universal approximation theorem, a single-layer network that's wide enough can theoretically approximate any function. However, in practice, having many neurons in a wide network is not always practical due to high computational demands. Deep networks, with multiple layers, are generally more efficient at modeling complex functions with fewer neurons compared to shallow networks. They are particularly good at learning different levels of data representation. For example, in facial recognition using CNNs, the initial layers might learn simple patterns like edges, and deeper layers can recognize more complex features like parts of a face. Shallow networks, though, have their own advantages. They are easier to train and don't face some common problems of deep networks, such as vanishing or exploding gradients. They are also more straightforward to understand. But, to capture complex functions, they might need many more neurons, making them less efficient for certain tasks. To sum up, deep networks are typically favored because they can learn complex patterns in a hierarchical, sturctured manners and do so efficiency with fewer neurons. But the study of shallow versus deep networks is still an active field in machine learning.
If you're new to the gradients (gradient descent) or need a refresher, my previous article offers a detailed exploration of gradient descent and popular optimizers, accessible here. This section, inspired by Hung-yi Lee's engaging lectures, blends my personal insights with his teachings. For those fluent in Chinese, I highly recommend his engaging machine learning lectures, available on YouTube. The initial step involves understanding the role of gradients in our process. Gradients enable us to calculate the partial derivative of the loss with respect to each parameter from different layers. Consider a scenario where we train our model using SGD (with Stochastic Gradient Descent) a batch size equal to 1. This means we use a single sample at a time to train our network. Through a certain magic, we can determine the partial derivative of the loss with respect to any weight, regardless of its depth in the network. For instance, within the network as below, we assume we already know the partial derivative of the loss with respect to the weights of the first layer. For example, the gradient of w1 at the first layer, denoted as ∂L(θ)/∂w1. Our goal is to understand what ∂L(θ)/∂w1 actually represents.
We will study backpropagation based on this network. Source: https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s Author's Note: A valuable technique I learned while practicing coding on Leetcode is to approach recursive functions by assuming a part of the task is already completed. This method helps in using the results of this assumed part to tackle larger problems. Adopting an attitude of assumed knowledge can provide comfort and ease your mind, fostering confidence as you delve into the topic. Essentially, it's about 'faking it till you make it' in problem-solving and even life attitude To dissect ∂L(θ)/∂w1 into comprehensible segments, we must explore the chain rule of partial derivatives. So, as is customary, let's begin with the question:
The chain rule is a fundamental technique in calculus, used for computing the derivative of a composite function. To illustrate what chain rules are, consider the following two examples:
Image created by the author.
To visualize the chain rule, imagine derivatives as streams of water in a landscape. Calculating the derivative of an element in a process is like tracing a water stream's journey. When functions are nested within each other, envision it as a small stream flowing into a river, then merging into the ocean. This represents how derivatives are multiplied together as they progress from small-scale to large-scale impacts. When two streams (derivatives) originate from different sources and converge, think of them as combining into a single stream. This illustrates the summing of two derivatives in the chain rule's context.
Imagine derivatives as streams of water in a landscape. Image created by the author using ChatGPT.
An intuitive but technically 'incorrect' approach to grasping the chain rule is to liken it to fraction manipulation. Visualize it as a scenario where the denominator cancels out with the numerator when they multiply together. While this visualization simplifies the concept, it's important to note that it's incorrect. Nonetheless, it serves as a useful aid in comprehending derivatives.
This image shows a simple but incorrect way to understand the chain rule. Image created by the author.
Returning to our neural network, it's helpful to visualize the connections within it as water streams. Here, the edges of the network symbolize the directional flow from input to output, with activation functions acting like complex gates altering the stream's properties. To understand how the weights in the first layer (w1) affect the loss, we trace the 'water stream' from the loss back to w1. To better understand how the first layer's weights (w1) affect the loss, envision tracing the 'water stream' from the loss back to w1. In the network diagram below, the red lines illustrate this water stream from the output back to w1, where z' and z'' are separate streams converging before an activation gate.
Image by source https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s, annotated by the author.
This stream flow analogy helps us reinterpret the partial derivative of the loss with respect to the first layer's weights (∂L(θ)/∂w1) more intuitively.
We can then dissect ∂L(θ)/∂w1, representing the general partial derivative of loss with respect to weight, into three parts using the chain rule:

After breaking down the partial derivatives into individual components, we can tackle the calculation by addressing each part separately. Let's begin with the simplest component by posing this question:
∂z/∂w1 represents the gradient of the output z before the activation function with respect to the weight direct associate with its own calculation. Since z , calculated as z_=_w_1_x_1+_w_2_x_2+_b, is a linear combination of inputs and weights, the derivative ∂z/∂w1 is simply the input associated with given weight w1, which is x1. This indicates that the gradient of zwith respect to its direct weight does not depend on the other layers or the loss function (error). It's a direct relationship: the partial derivative equals to the input that w1 multiplies in the forward pass. For a bias term b, the derivative is always 1 since a bias is a constant term.
Image by source https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s, annotated by the author.
To clarify with examples, let's consider two scenarios. Starting with the first scenario where z is in the first hidden layer of the network. As highlighted in the graph with z and its inputs marked in red, we can calculate the derivatives by using the value of related input directly.
If the layer is the other hidden layer that are not direct associate with input data, the principle applies to those hidden layers as well. The partial derivative of a linear function with respect to its weight is the input to that weight. In the graph, for subsequent layers like z' and z'' in the network, the partial derivatives with respect to their associated weights, such as _w_3 and _w_4, are the outputs of the previous layer's activation function, which in this case is a. I highlighted those relationships in blue.
In summary, the computation of the partial derivative of z(the output before activation) with respect to its weights is straightforward: it's the input value to that weight. The derivative with respect to the bias is always 1. One can trace back along the edge of the weight in the network graph to find the corresponding input, and this input is the value of the partial derivative of the output z respect to the weight. This part of the backpropagation process does not require any "backward" information from the loss and is determined during the forward pass while processing the input data.
The computation of ∂a/∂z is more straightforward compared to ∂z/∂w1, considering that a is just a function result of z. Specifically, a = σ(z), where σ(z) represents the activation function. For those unfamiliar with activation functions, an activation function like σ_(z) are used to introduce non-linearity into the neural network. Using our analogy of water streams, you can think it as a 'water gate' that altering the water stream of computation in a non-linear fashion, enabling the network to capture complex patterns that are non-linear. This non-linearity is vital for the network's ability to capture the complex, non-linear underlying patterns. As activation functions are crucial in neural networks and transforming computations to non-linearity, the derivative ∂a/∂z is a key component in backpropagation. It helps adjust gradients as they traversal the network reversely. Given a = σ(z), the derivative ∂a/∂z is simply σ′(z), the derivative of the activation function with respect to the original input z. Calculating σ ′(z) is quite simple. It involves plugging the input z into the derivative of the activation function. The derivative of the activation function, is simply another function which doesn't require any information about the loss of current prediction. **** For instance, if the activation function is the sigmoid function, and its derivative** σ′(z) can be defined in terms of the function itself as _σ′ (z**)=σ(z)(1−** σ(z)). In practice, our program can define σ'(z) before trainin**g. We then input z into σ'(z) to get the partial derivative ∂a/∂z. Thus, like ∂z/∂w1, ∂a/∂z doesn't need loss information and can be computed during the forward pass. This derivative is then used in the chain rule during backpropagation to find the gradient of the loss with respect to the weights.
I'm glad you noticed that. Let's recap our discussion so far:
We've established that the calculation of ∂ z /∂w_1 is straightforward because it is the input associated with weight w1. Similarly, for the activation function's output a , represented as a=σ(z), the derivative ∂a_/∂ z is just σ_′(_z), which is the derivative of the activation function. Both components' calculation are independent of the loss function and can be either pre-defined ahead of training process or pre-computed during the forward pass.
Now, the remaining part involves ∂ L /∂ a , which tells us how changes in the activation output a affect the overall loss L. Imagine the entire neural network as a cake factory's production line, tasked with baking, packaging, and shipping cakes to stores. If a cake arrives damaged (akin to a poor prediction), it's necessary to backtrack and identify which stage of the process was responsible for the damage and to what extent.
Imagine the entire neural network as a cake factory's production line. Image created by the author using ChatGPT.
In backpropagation, we use the chain rule to decompose ∂ L /∂ a. In our example network, the a is part of input related to two outputs, z ′ and z ′′. Then when trying to understand how much loss a contributes to the loss, we need to gather information from those two outputs to measure the impact.
Image by source https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s, annotated by the author.
This is analogous to the cake production line, where ∂ z ′/∂ a and ∂ z ′′/∂ a represent the contribution of a to each output, and we must trace the impact back from the loss through these channels.
Given that
We combine these with the activation function derivative ∂a/∂z to get
This is key to understanding why the process is named as backpropagation.
This formula shows that ∂ L/∂ zis influenced by the gradients from the next layer, showcasing the 'backward' aspect of the computation. This is key to understanding why the process is named as backpropagation.
To update weights throughout the neural network, we calculate the partial derivative of the loss with respect to each weight, ∂L/∂w. Forward calculation (from input to output layer) would be inefficient, requiring repeated computation of ∂L/∂z for each layer starting from the input layer. Using the function above, a more efficient approach is to compute ∂L/∂z starting from the output layer and moving backwards to the input layer. This method involves storing the result and reusing the current layer's ∂L/∂z for the preceding layers. Be aware that, to find ∂L/∂z for the (n-1)th layer, we only need the derivative of the loss with respect to the nth layer. So this process allows for calculating each layer's derivative just once, in a single, elegant and backward pass.
Let's consider ∂ L /∂ z calculation for the output layer. Here, z is the input to the output layer, which gets transformed into the prediction y-hat by the activation function σ_(_z). Then, the prediction (y-hat) is used to calculate the loss, expressed as L(y, y-hat) , where L is the loss function. Then we'd apply chain rule to define the calculation of ∂ L /∂ z for the last layer into two parts.

You are correct that the calculations with a larger batch size do differ slightly, but the fundamental calculations we discussed for backpropagation remain valid. It primarily involves an additional adding up step.
When a batch size > 1, the loss during the forward pass is the average loss across all samples in the batch. So, the partial derivative of the loss with respect to weight, ∂L/∂w1, is the average of the derivatives of individual losses (∂l/∂w) for all data points in the batch.
Mathematically, for batch size n, the gradient of loss L with respect to weight w1 is calculated as
Here i represents the loss for the ith sample within the batch. It's important to note we use the average of the gradients here. By calculating the average, we ensure that the update to the weight is reflective of the average direction in which the loss decreases across all samples in the batch.
Alright, with our discussion, let's apply this knowledge to understand the code you've got. It's an excellent way to grasp complex concepts. As usual, let's shape this into a question:
Let's view the calculation steps by step. All the code shown here is from the Python tutorial on Machine Learning Mastery .
Define activation functions and their derivatives.
The code uses sigmoid function as activation function. To calculate the derivatives of the activation output with respect to its input, the code defines the sigmoid function as transfer and a transfer_derivative function for its derivative.
python
# Transfer neuron activation
def transfer(activation):
return 1.0 / (1.0 + exp(-activation))
# Calculate the derivative of an neuron output
def transfer_derivative(output):
return output * (1.0 - output)
The backward_propagate_error function involves looping backwards from output to input layer. In the function, the variableerror represents ∂L/∂a. It differentiates between the output and hidden layers for ∂L/∂a calculation.
neuron['output'] - expected[j]. This part of code can be confusing, because typically we'd use MSE (mean squared error) and CE (cross entropy) as loss function. Also the partial derivative of loss with repsect to prediction error is not obvious in the code.python
def backward_propagate_error(network, expected):
for i in reversed(range(len(network))):
layer = network[i]
# calculate the loss forr each layer
if i != len(network)-1:
...
else:
# ∂L/∂a of the output layer
for j in range(len(layer)):
neuron = layer[j]
errors.append(neuron['output'] - expected[j])
delta (representing ∂ L /∂z) of the following layer.python
# Backpropagate error and store in neurons
def backward_propagate_error(network, expected):
for i in reversed(range(len(network))):
layer = network[i]
errors = list()
# calculate the loss forr each layer
if i != len(network)-1:
...
# ∂L/∂a of the hidden layer
for neuron in network[i + 1]:
error += (neuron['weights'][j] * neuron['delta'])
errors.append(error)
else:
...
Here, we compute ∂ L /∂z as ∂ L /∂a (represented as errors in the code)* σ'(z), and store the result as neuron['delta']
python
# Backpropagate error and store in neurons
def backward_propagate_error(network, expected):
for i in reversed(range(len(network))):
layer = network[i]
errors = list()
# calculate the partial derivative of the loss with repsect to the input before activation
for j in range(len(layer)):
neuron = layer[j]
neuron['delta'] = errors[j] * transfer_derivative(neuron['output'])
Finally, we'd update the weights at the corresponding layer using ∂ L /∂w = ∂ L /∂z* ∂ z /∂w.The weights are adjusted based on the delta (representing ∂ L /∂z) and inputs, while for bias term we will only need delta.
python
# Update network weights with error
def update_weights(network, row, l_rate):
for i in range(len(network)):
inputs = row[:-1]
if i != 0:
inputs = [neuron['output'] for neuron in network[i - 1]]
for neuron in network[i]:
for j in range(len(inputs)):
neuron['weights'][j] -= l_rate * neuron['delta'] * inputs[j]
neuron['weights'][-1] -= l_rate * neuron['delta'] # bias term the input is 1
Note that the code is based on SGD with a batch size of 1. Therefore, the code doens't include the calculations that involving averaging of loss or partial derivatives over multiple samples.
Backpropagation calculation is a akin to the reversed version of forward pass, largely because:
However, they are still quite different:
Understanding backpropagation is crucial, even with deep learning frameworks like PyTorch and TensorFlow. A thorough understanding of its calculation provides an intuitive grasp of various challenges and training tricks in deep learning, without needing to memorize them. A key insight gained from understanding backpropagation is
Recall our discussion on calculating ∂ a /∂ z. When implementing backpropagation in code, to save memory, we'd define both the activation function and its derivative, which explains why tutorials often list derivatives alongside activation functions. These derivatives are as essential as the activation functions themselves and often predefined before modeling.
Activation Functions and their Derivatives. Source: https://dwaithe.github.io/images/activationFunctions.png
Consider the computation of ∂ L /∂ _z _during backpropagation. This calculation relies on the outputs from subsequent layers, and it has a pattern:__the gradient for earlier layers is a product of the activation function derivatives at each successive layer._For instance, assuming our example network has one more layers after z' and z'', with weights w_5 and w 6, this calculation becomes an intricate multiplication of these derivatives.
If we choose sigmoid and tanh as our activation function, then they would may lead us to the gradient vanishing problem. Because the derivatives of functions like sigmoid and tanh have very small range. The sigmoid derivative ranges between 0 and 0.25, while tanh's derivative lies between 0 and 1. As a result, when multiplied, their products tend to diminish progressively, leading to progressively smaller gradients. This reduction in gradient magnitude causes the earlier layers to receive very small gradient updates, keeping them away from effective learning and parameter adjustment.
Source: https://i0.wp.com/neptune.ai/wp-content/uploads/2022/10/Vanishing-and-Exploding-Gradients-in-Neural-Network-Models-Debugging-Monitoring-and-Fixing-Practical-Guide_7.png?resize=636%2C497&ssl=1
One solution is to use an activation function whose derivative has a broader range. ReLU, for example, returns either 1 or 0, effectively addressing the vanishing gradient issue. However, ReLU has its drawback, because it can lead the multiplication of derivatives become 0. Consequently, neurons receive no updates, become inactive, and fail to contribute to model learning. This problem is known as "dying ReLU".
In summary, a thorough understanding of backpropagation can be very beneficial. It's a cornerstone in developing effective neural network models and troubleshooting training problems.
(Unless otherwise noted, all images are by the author)
If you're enjoying this series, remember that your interactions - claps, comments, and follows - do more than just support; they're the driving force that keeps this series going and inspires my continued sharing. Other posts in this series:
If you liked the article, you can find me on LinkedIn .
https://machinelearningmastery.com/implement-backpropagation-algorithm-scratch-python/ Please accept cookies to access this content Please accept cookies to access this content
All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more. Register for freeSign in to your account
Written By
See all from Amy Ma Deep DivesArtificial IntelligenceCourage To Learn MlData ScienceMachine Learning Share This Article
Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program. Write for TDS
Machine Learning August 2025: logging, lab notebooks, overnight runs Pascal Janetzky August 31, 20254 min read
Machine Learning Label your data programmatically! Albers Uzila May 23, 20223 min read
Deep Learning This forward-hook detector catches NaNs and exploding gradients at the exact layer and batch they first appear — with ~3–4 ms overhead vs ~7–8 ms for set_detect_anomaly on CPU. On GPU, the gap becomes significantly larger. Emmimal P Alexander April 28, 202610 min read
Programming Making a non-scientific benchmark with Python and Llama-CPP Dmitrii Eliuseev April 27, 202410 min read
Programming By building an interior designer in ComfyUI Ida Silfverskiold January 21, 202521 min read
Deep Learning Data, Computational resources, Algorithms and Open-sourced frameworks Rukshan Pramoditha July 10, 20214 min read
Machine Learning Multi-Model Endpoints with Amazon SageMaker Ram Vegiraju September 2, 20216 min read
Machine Learning A detailed explanation of how random forest machine learning algorithm works, what makes it superior to decision trees, and how you can... Saul Dobilas February 7, 20219 min read
Data Science Hint: There's No Exact Answer JB September 4, 20217 min read
Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals. Subscribe to Our NewsletterWrite For TDS•About•Advertise•Privacy Policy•Terms of Use © Insight Media Group, LLC 2026•The New Stack•roadmap.sh•Creator Network
Close