![Revisit consent button](../images/body-df29beacd7496220cc94.svg)
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 ![](../images/body-2159bb67f3de8ad870eb.svg)
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 Search[](https://towardsdatascience.com/)Toggle Mobile Navigation
[](https://towardsdatascience.com/)
Publish AI, ML & data-science insights to a global community of data professionals.
Sign in[Submit an Article](https://write.insightmediagroup.io)
[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)
* * *
[Write For TDS](https://towardsdatascience.com/submissions/)
[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
# Courage to Learn ML: Explain Backpropagation from Mathematical Theory to Coding Practice
Transforming Backpropagation's Complex Math into Manageable and Easy-to-Learn Bites
[Amy Ma](https://towardsdatascience.com/author/amyma101/)
January 17, 202420 min read
![Image created by the author using ChatGPT.](../images/000.png)
Image created by the author using ChatGPT.
Welcome back to the latest chapter of '[Courage to Learn ML](https://towardsdatascience.com/tagged/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](https://machinelearningmastery.com/implement-backpropagation-algorithm-scratch-python/), 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](https://roadmap.sh/ai-engineer), [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.
  * Understanding backpropagation and its connection to gradient Descent
  * Exploring the preference for depth over width in DNNs and the rarity of shallow, wide networks.
  * What is the chain rule?
  * Breaking down backpropagation calculation into 3 components and examining each thoroughly. Why is it called **back** propagation?
  * Understand backpropagation through straightforward Python code
  * Gradient vanishing and common preference in activation functions


* * *
Let's start with the fundamental why -
## What is backpropagation and how is it related to gradient descent?
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.
## So the hard part of training DNN is due to multiple layers. But, before talking more about backpropation, I'm curious why DNNs typically go deeper rather than wider. Why aren't shallow but wide networks popular?
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.
## Now, let's explore backpropagation in detail and utilize the code snippets as a resource to deepen our understanding of the concept.
> 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](https://towardsdatascience.com/courage-to-learn-ml-a-detailed-exploration-of-gradient-descent-and-popular-optimizers-022ecf97be7d#9de7-b3f46fe366fb). 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](https://www.youtube.com/@HungyiLeeNTU).
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&amp;t=1510s](../images/001.png)
We will study backpropagation based on this network. Source: [https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s](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:
## What is the chain rule?
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:
  * If y = f(x) and x = g(t), this implies y = f(g(t)). Therefore, the derivative of y with respect to t (∂y/∂t) is calculated as the **product** of the derivative of y with respect to x (∂y/∂x) and the derivative of x with respect to t (∂x/∂t). So we have ∂y/∂t = ∂y/∂x * ∂x/∂t


![Image created by the author.](../images/002.png)
Image created by the author.
  * If z = f(x, y), with y = g(t) and x = q(t), the derivative of z with respect to t (∂z/∂t) is **the sum of the product** of the derivative of z with respect to y (which is ∂z/∂y) and the derivative of y with respect to t (which is ∂y/∂t), and the product of the derivative of z with respect to x (∂z/∂x) and the derivative of x with respect to t (∂x/∂t). So we have ∂z/∂t = (∂z/∂x _∂x/∂t) + (∂z/∂y_ ∂y/∂t).


![](../images/body-bf522efbf93cf06abb47.png)
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.](../images/003.png)
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.](../images/004.png)
This image shows a simple but incorrect way to understand the chain rule. Image created by the author.
## How is the chain rule applied to our calculation of ∂L(θ)/∂w1?
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&amp;t=1510s, annotated by the author.](../images/005.png)
Image by source [https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s](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.
![](../images/body-04f322dd0a8c8cfc9bf4.png)
We can then dissect ∂L(θ)/∂w1, representing the general partial derivative of loss with respect to weight, into three parts using the chain rule:
![](../images/body-ba67e2f39b43ce0f48f7.png)
  * The partial derivative of the overall loss relative to the current layer, taking into account its role as the input for subsequent layers. This reflects the portion of the loss that can be influenced or contributed by this layer. It's important to note that the current layer's output is influenced by the preceding layers.
  * The partial derivative of the activation function's output a with respect to its input z, where a = 𝜎(z). Since the activation function is like a gate altering the stream's characteristics, understanding its impact on the stream becomes crucial when allocating loss to different layers.
  * The partial derivative of a neuron's direct output, z, with respect to its weight, w1. In the formula z_=_w_1_x_1+_w_2_x_2+_b, **z is the direct outcome of w1** and represents the stream prior to encountering the activation function.


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:
## How do we compute ∂z/∂w1, which is the partial derivative of z with respect to the weight that directly determines it in a linear fashion?
∂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** _**z**_**with 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&amp;t=1510s, annotated by the author.](../images/006.png)
Image by source [https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s](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.
![](../images/body-5fee1c3eac948c6ca7dc.png)
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.
![](../images/body-eb80545fb255ce500d2a.png)
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.
## So, the calculation of ∂z/∂w1 isn't actually a "backward" process. It's simply equal to the input of the neuron. How about the partial derivative of the activation output with respect to its input, ∂a/∂z?
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.
## Considering our discussion thus far, when computing ∂L/∂w1, two of the three components do not require loss information or input from later layers. Then why do we refer the calculation process as 'backpropagation'?
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&#039;s production line. Image created by the author using ChatGPT.](../images/007.png)
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&amp;t=1510s, annotated by the author.](../images/008.png)
Image by source [https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s](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.
![](../images/body-08bad1d356797e598a90.png)
Given that
![](../images/body-4dd9892b2e5b1be2812e.png)
We combine these with the activation function derivative ∂a/∂z to get
![This is key to understanding why the process is named as backpropagation.](../images/009.png)
This is key to understanding why the process is named as backpropagation.
This formula shows that **∂** _**L**_**/∂** _**z**_**is 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.
## So, we recursively compute ∂L/∂z for each layer backwards. Then, how do we calculate the partial derivatives of the loss with respect to the output layer's z, which serves as the first value of ∂L/∂z to start the process?
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.
  * The derivative of the loss function with respect to the network's prediction, which depends on the loss function type. For instant, for regression task we often use MSE (Mean Squared Error). While for multi-class classification, we'd choose CE (cross entropy) as loss function. Then for single prediction, the partial derivative of the loss with respect to the prediction would be


![](../images/body-6b5ed60ee6cb6e77a8cb.png)
  * The derivative of the prediction (y-hat) with respect to the last layer activation's input, similar to ∂a/∂z, is the derivative of the last layer's activation function, σ'(z).


## Our discussions so far about backpropagation have focused on using SGD (Stochastic Gradient Descent) with a batch size = 1. What if we use a larger batch size for training, would that alter the calculations?
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
![](../images/body-46d2b7a12e22026cdd07.png)
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:
## Based on our discussion, how to combine these elements to construct the backpropagation calculation? How to use our insights to decode this code snippet?
Let's view the calculation steps by step. _All the code shown here is from the Python tutorial on_[ _Machine Learning Mastery_](https://machinelearningmastery.com/implement-backpropagation-algorithm-scratch-python/) _._
**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)
```

###  **Calculate ∂** _**L**_**/∂a.**
The `backward_propagate_error` function involves looping backwards from output to input layer. In the function, the variable`error` represents ∂L/∂a. It differentiates between the output and hidden layers for ∂L/∂a calculation.
  * **For the output layer,** the error is simply the difference between the output and expected value. The loss function used here is the prediction error as (y - y_hat). The derivative for this loss function is -1. Therefore, ∂L/∂a is calculated as `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]) 
```

  * **For hidden layers,** it's calculated based on the weights and `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: 
     ... 
```

###  **Calculate ∂** _**L**_**/∂z.**
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']) 
```

###  **Calculate ∂** _**L**_**/∂w to adjust weights.**
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.
## You know, backpropagation kind of like the reverse of the forward pass, doesn't it? Is that a fair way to look at it?
Backpropagation calculation is a akin to the reversed version of forward pass, largely because:
  * The derivative of activation function mirrors the role of activation function in forward propagation.
  * The ∂L/∂z calculation is like calculating z in forward pass, adding up the multiplications of the previous layer's outputs and weights. For backpropagation we use the outputs of the next layer.


However, they are still quite different:
  * **Different starting points.** Forward pass begins with input data X, while backpropagation starts from the loss, making the choice of loss function pivotal.
  * **Different purpose.** Forward propagation aims to generate predictions based on given data. While the goal of backpropagation is to train the model. We do so by djusting the model's parameters based on the comparison between predictions and actual values.
  * **Calculation dependency.** Backpropgation needs the result of the forward pass, and use the chain rule integrate elements from the forward pass and partial derivatives of loss from following layers. So backpropagation is inseparabel from the forward propagation process.


## Why is it important for us to understand the intricate details of backpropagation's calculations?
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
## How does backpropagation inform the choice of activation functions?
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](../images/body-54059ee811020cba82b7.png)
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.
![](../images/body-4d0b9997343e606cb08f.png)
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&amp;ssl=1](../images/body-c41fc1c8b69dc6214b65.png)
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](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 t[his series](http://towardsdatascience.com/tagged/courage-to-learn-ml), 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:
  * [Courage to Learn ML: Demystifying L1 & L2 Regularization (part 1)](https://towardsdatascience.com/understanding-l1-l2-regularization-part-1-9c7affe6f920)
  * [Courage to Learn ML: Decoding Likelihood, MLE, and MAP](https://towardsdatascience.com/courage-to-learn-ml-decoding-likelihood-mle-and-map-65218b2c2b99)
  * [Courage to Learn ML: A Deeper Dive into F1, Recall, Precision, and ROC Curves](https://medium.com/p/d5c0a46e5eb7)
  * [Courage to Learn ML: An In-Depth Guide to the Most Common Loss Functions](https://medium.com/p/84a6b07cca17)
  * [Courage to Learn ML: A Detailed Exploration of Gradient Descent and Popular Optimizers](https://medium.com/p/022ecf97be7d)


* * *
_**If you liked the article, you can find me on**_[ _**LinkedIn**_](https://www.linkedin.com/in/amyma101/) _**.**_
## **Reference:**
<https://machinelearningmastery.com/implement-backpropagation-algorithm-scratch-python/>
Please accept cookies to access this content
Please accept cookies to access this content
## Register Now to Continue Reading
### Unlock Towards Data Science with a Free Account
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
* * *
![](../images/body-bf30693e05bb856f0cb2.png)
Written By
## [Amy Ma](https://towardsdatascience.com/author/amyma101/)
[See all from Amy Ma](https://towardsdatascience.com/author/amyma101/)
[Deep Dives](https://towardsdatascience.com/tag/deep-dives/)[Artificial Intelligence](https://towardsdatascience.com/tag/artificial-intelligence/)[Courage To Learn Ml](https://towardsdatascience.com/tag/courage-to-learn-ml/)[Data Science](https://towardsdatascience.com/tag/data-science/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)
Share This Article
  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fcourage-to-learn-ml-explain-backpropagation-from-mathematical-theory-to-coding-practice-21e670415378%2F&title=Courage%20to%20Learn%20ML%3A%20Explain%20Backpropagation%20from%20Mathematical%20Theory%20to%20Coding%20Practice)
  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fcourage-to-learn-ml-explain-backpropagation-from-mathematical-theory-to-coding-practice-21e670415378%2F&title=Courage%20to%20Learn%20ML%3A%20Explain%20Backpropagation%20from%20Mathematical%20Theory%20to%20Coding%20Practice)
  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fcourage-to-learn-ml-explain-backpropagation-from-mathematical-theory-to-coding-practice-21e670415378%2F&text=Courage%20to%20Learn%20ML%3A%20Explain%20Backpropagation%20from%20Mathematical%20Theory%20to%20Coding%20Practice)


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](https://towardsdatascience.com/submissions/)
## Related Articles
  * [![](../images/010.jpg)](https://towardsdatascience.com/this-months-machine-learning-lessons-learned/)
## [The Machine Learning Lessons I’ve Learned This Month](https://towardsdatascience.com/this-months-machine-learning-lessons-learned/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
August 2025: logging, lab notebooks, overnight runs
[Pascal Janetzky](https://towardsdatascience.com/author/pascaljanetzky/)
August 31, 20254 min read
  * [![](../images/011.jpg)](https://towardsdatascience.com/weak-supervision-with-snorkel-for-multilabel-classification-tasks-c7af4990ea45/)
## [Weak Supervision: Labeling Your Data Without Actually Labeling It 🤔](https://towardsdatascience.com/weak-supervision-with-snorkel-for-multilabel-classification-tasks-c7af4990ea45/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
Label your data programmatically!
[Albers Uzila](https://towardsdatascience.com/author/dwiuzila/)
May 23, 20223 min read
  * [![](../images/012.jpg)](https://towardsdatascience.com/pytorch-nans-are-silent-killers-i-built-a-3ms-hook-to-catch-them-at-the-exact-layer/)
## [PyTorch NaNs Are Silent Killers — So I Built a 3ms Hook to Catch Them at the Exact Layer](https://towardsdatascience.com/pytorch-nans-are-silent-killers-i-built-a-3ms-hook-to-catch-them-at-the-exact-layer/)
[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/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](https://towardsdatascience.com/author/emmimalp.alexander/)
April 28, 202610 min read
  * [![](../images/013.jpeg)](https://towardsdatascience.com/llama-2-vs-llama-3-a-tic-tac-toe-battle-between-models-7301962ca65d/)
## [Llama-2 vs. Llama-3: a Tic-Tac-Toe Battle Between Models](https://towardsdatascience.com/llama-2-vs-llama-3-a-tic-tac-toe-battle-between-models-7301962ca65d/)
[Programming](https://towardsdatascience.com/category/programming/)
Making a non-scientific benchmark with Python and Llama-CPP
[Dmitrii Eliuseev](https://towardsdatascience.com/author/dmitryelj/)
April 27, 202410 min read
  * [![](../images/014.png)](https://towardsdatascience.com/learn-to-build-advanced-ai-image-applications-9c98d0f1f930/)
## [Learn to Build Advanced AI Image Applications](https://towardsdatascience.com/learn-to-build-advanced-ai-image-applications-9c98d0f1f930/)
[Programming](https://towardsdatascience.com/category/programming/)
By building an interior designer in ComfyUI
[Ida Silfverskiold](https://towardsdatascience.com/author/ilsilfverskiold/)
January 21, 202521 min read
  * [![](../images/015.jpeg)](https://towardsdatascience.com/emerging-of-machine-learning-and-deep-learning-ddf8e3e5e85e/)
## [Emerging of Machine Learning and Deep Learning](https://towardsdatascience.com/emerging-of-machine-learning-and-deep-learning-ddf8e3e5e85e/)
[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)
Data, Computational resources, Algorithms and Open-sourced frameworks
[Rukshan Pramoditha](https://towardsdatascience.com/author/rukshanpramoditha/)
July 10, 20214 min read
  * [![](../images/016.jpg)](https://towardsdatascience.com/deploy-multiple-tensorflow-models-to-one-endpoint-65bea81c3f2f/)
## [Deploy Multiple TensorFlow Models to One Endpoint](https://towardsdatascience.com/deploy-multiple-tensorflow-models-to-one-endpoint-65bea81c3f2f/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
Multi-Model Endpoints with Amazon SageMaker
[Ram Vegiraju](https://towardsdatascience.com/author/ram-vegiraju/)
September 2, 20216 min read
  * [![](../images/017.png)](https://towardsdatascience.com/random-forest-models-why-are-they-better-than-single-decision-trees-70494c29ccd1/)
## [Random Forest Models: Why Are They Better Than Single Decision Trees?](https://towardsdatascience.com/random-forest-models-why-are-they-better-than-single-decision-trees-70494c29ccd1/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/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](https://towardsdatascience.com/author/solclover/)
February 7, 20219 min read
  * [![](../images/018.jpeg)](https://towardsdatascience.com/what-makes-a-great-data-analyst-f6577cef81a3/)
## [What Makes a Great Data Analyst?](https://towardsdatascience.com/what-makes-a-great-data-analyst-f6577cef81a3/)
[Data Science](https://towardsdatascience.com/category/data-science/)
Hint: There's No Exact Answer
[JB](https://towardsdatascience.com/author/josephburton06/)
September 4, 20217 min read


  * [YouTube](https://www.youtube.com/c/TowardsDataScience)
  * [X](https://x.com/TDataScience)
  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)
  * [Threads](https://www.threads.net/@towardsdatascience)
  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)


[](https://towardsdatascience.com/)
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 Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)
© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)
####  Recommended Articles 
Close
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ "How Relevance Models Foreshadowed Transformers for NLP")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ "Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ "The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ "Does Your Company Have a Data Strategy?")


