{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Amy Ma",
  "title_listed": "Courage to Learn ML: Explain Backpropagation from Mathematical Theory to Coding Practice",
  "keywords": "",
  "domain": "机器学习",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/courage-to-learn-ml-explain-backpropagation-from-mathematical-theory-to-coding-practice-21e670415378/",
  "publish_date": "2024-01-17",
  "corpus_stage": "",
  "notes": "",
  "id": "d09fdca7178e",
  "collected_at": "2026-10-02T07:53:34",
  "title": "Courage to Learn ML: Explain Backpropagation from Mathematical Theory to Coding Practice | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe 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.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe 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\nNecessaryAlways Active\nNecessary 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.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis 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.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress 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.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis 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.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo 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. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes 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.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe 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.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical 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.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot 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).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot 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.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle 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.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance 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.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement 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.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter 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.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter 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.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube 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.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[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/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\n# Courage to Learn ML: Explain Backpropagation from Mathematical Theory to Coding Practice\nTransforming Backpropagation's Complex Math into Manageable and Easy-to-Learn Bites\n[Amy Ma](https://towardsdatascience.com/author/amyma101/)\nJanuary 17, 202420 min read\n![Image created by the author using ChatGPT.](../images/000.png)\nImage created by the author using ChatGPT.\nWelcome 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.\nThis 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.\nAs always, here's a list of the topics we'll be exploring today:\nLearn 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.\n  * Understanding backpropagation and its connection to gradient Descent\n  * Exploring the preference for depth over width in DNNs and the rarity of shallow, wide networks.\n  * What is the chain rule?\n  * Breaking down backpropagation calculation into 3 components and examining each thoroughly. Why is it called **back** propagation?\n  * Understand backpropagation through straightforward Python code\n  * Gradient vanishing and common preference in activation functions\n\n\n* * *\nLet's start with the fundamental why -\n## What is backpropagation and how is it related to gradient descent?\nGradient 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.\nHowever, 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.\nThis 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.\n## 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?\nThis 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.\nDeep 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.\nShallow 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.\nTo 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.\n## Now, let's explore backpropagation in detail and utilize the code snippets as a resource to deepen our understanding of the concept.\n> 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).\nThe 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.\nConsider 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.\n![We will study backpropagation based on this network. Source: https://www.youtube.com/watch?v=ibJpTrp5mcE&amp;t=1510s](../images/001.png)\nWe 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)\n> 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\nTo 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:\n## What is the chain rule?\nThe 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:\n  * 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\n\n\n![Image created by the author.](../images/002.png)\nImage created by the author.\n  * 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).\n\n\n![](../images/body-bf522efbf93cf06abb47.png)\nTo 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.\n![Imagine derivatives as streams of water in a landscape. Image created by the author using ChatGPT.](../images/003.png)\nImagine derivatives as streams of water in a landscape. Image created by the author using ChatGPT.\n> 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.\n![This image shows a simple but incorrect way to understand the chain rule. Image created by the author.](../images/004.png)\nThis image shows a simple but incorrect way to understand the chain rule. Image created by the author.\n## How is the chain rule applied to our calculation of ∂L(θ)/∂w1?\nReturning 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.\n![Image by source https://www.youtube.com/watch?v=ibJpTrp5mcE&amp;t=1510s, annotated by the author.](../images/005.png)\nImage by source [https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s](https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s), annotated by the author.\nThis stream flow analogy helps us reinterpret the partial derivative of the loss with respect to the first layer's weights (∂L(θ)/∂w1) more intuitively.\n![](../images/body-04f322dd0a8c8cfc9bf4.png)\nWe can then dissect ∂L(θ)/∂w1, representing the general partial derivative of loss with respect to weight, into three parts using the chain rule:\n![](../images/body-ba67e2f39b43ce0f48f7.png)\n  * 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.\n  * 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.\n  * 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.\n\n\nAfter 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:\n## 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?\n∂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.\n![Image by source https://www.youtube.com/watch?v=ibJpTrp5mcE&amp;t=1510s, annotated by the author.](../images/006.png)\nImage by source [https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s](https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s), annotated by the author.\nTo 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.\n![](../images/body-5fee1c3eac948c6ca7dc.png)\nIf 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.\n![](../images/body-eb80545fb255ce500d2a.png)\nIn 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.\n## 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?\nThe 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.\nAs 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.\nCalculating _σ_ ′(_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.\n**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.\n## 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'?\nI'm glad you noticed that. Let's recap our discussion so far:\nWe'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.\nNow, 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.\n![Imagine the entire neural network as a cake factory&#039;s production line. Image created by the author using ChatGPT.](../images/007.png)\nImagine the entire neural network as a cake factory's production line. Image created by the author using ChatGPT.\nIn 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.\n![Image by source https://www.youtube.com/watch?v=ibJpTrp5mcE&amp;t=1510s, annotated by the author.](../images/008.png)\nImage by source [https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s](https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s), annotated by the author.\nThis 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.\n![](../images/body-08bad1d356797e598a90.png)\nGiven that\n![](../images/body-4dd9892b2e5b1be2812e.png)\nWe combine these with the activation function derivative ∂a/∂z to get\n![This is key to understanding why the process is named as backpropagation.](../images/009.png)\nThis is key to understanding why the process is named as backpropagation.\nThis 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.\nTo 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.\n## 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?\nLet'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.\n  * 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\n\n\n![](../images/body-6b5ed60ee6cb6e77a8cb.png)\n  * 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).\n\n\n## 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?\nYou 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.\nWhen 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.\nMathematically, for batch size n, the gradient of loss L with respect to weight w1 is calculated as\n![](../images/body-46d2b7a12e22026cdd07.png)\nHere 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.\nAlright, 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:\n## Based on our discussion, how to combine these elements to construct the backpropagation calculation? How to use our insights to decode this code snippet?\nLet'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/) _._\n**Define activation functions and their derivatives**.\nThe 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.\npython\n\n```\n# Transfer neuron activation\ndef transfer(activation):\n  return 1.0 / (1.0 + exp(-activation))\n\n# Calculate the derivative of an neuron output\ndef transfer_derivative(output):\n return output * (1.0 - output)\n```\n\n###  **Calculate ∂** _**L**_**/∂a.**\nThe `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.\n  * **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.\n\n\npython\n\n```\ndef backward_propagate_error(network, expected):\n for i in reversed(range(len(network))):\n  layer = network[i]\n  # calculate the loss forr each layer\n  if i != len(network)-1:\n   ...\n  else: \n      # ∂L/∂a of the output layer  \n   for j in range(len(layer)):\n    neuron = layer[j]\n    errors.append(neuron['output'] - expected[j]) \n```\n\n  * **For hidden layers,** it's calculated based on the weights and `delta` (representing ∂ _L_ /∂z) of the following layer.\n\n\npython\n\n```\n# Backpropagate error and store in neurons\ndef backward_propagate_error(network, expected):\n for i in reversed(range(len(network))):\n  layer = network[i]\n  errors = list()\n  # calculate the loss forr each layer\n  if i != len(network)-1:\n   ...\n        # ∂L/∂a of the hidden layer  \n    for neuron in network[i + 1]: \n     error += (neuron['weights'][j] * neuron['delta']) \n    errors.append(error)\n  else: \n     ... \n```\n\n###  **Calculate ∂** _**L**_**/∂z.**\nHere, we compute ∂ _L_ /∂z as ∂ _L_ /∂a (represented as `errors` in the code)* σ'(z), and store the result as `neuron['delta']`\npython\n\n```\n# Backpropagate error and store in neurons\ndef backward_propagate_error(network, expected):\n  for i in reversed(range(len(network))):\n  layer = network[i]\n  errors = list()\n # calculate the partial derivative of the loss with repsect to the input before activation\n  for j in range(len(layer)):\n   neuron = layer[j] \n   neuron['delta'] = errors[j] * transfer_derivative(neuron['output']) \n```\n\n###  **Calculate ∂** _**L**_**/∂w to adjust weights.**\nFinally, 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`.\npython\n\n```\n# Update network weights with error\ndef update_weights(network, row, l_rate):\n  for i in range(len(network)):\n    inputs = row[:-1]\n    if i != 0:\n      inputs = [neuron['output'] for neuron in network[i - 1]]\n    for neuron in network[i]:\n      for j in range(len(inputs)):\n        neuron['weights'][j] -= l_rate * neuron['delta'] * inputs[j] \n      neuron['weights'][-1] -= l_rate * neuron['delta'] # bias term the input is 1\n```\n\n> 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.\n## You know, backpropagation kind of like the reverse of the forward pass, doesn't it? Is that a fair way to look at it?\nBackpropagation calculation is a akin to the reversed version of forward pass, largely because:\n  * The derivative of activation function mirrors the role of activation function in forward propagation.\n  * 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.\n\n\nHowever, they are still quite different:\n  * **Different starting points.** Forward pass begins with input data X, while backpropagation starts from the loss, making the choice of loss function pivotal.\n  * **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.\n  * **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.\n\n\n## Why is it important for us to understand the intricate details of backpropagation's calculations?\nUnderstanding 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\n## How does backpropagation inform the choice of activation functions?\nRecall 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.\n![Activation Functions and their Derivatives. Source: https://dwaithe.github.io/images/activationFunctions.png](../images/body-54059ee811020cba82b7.png)\nActivation Functions and their Derivatives. Source: <https://dwaithe.github.io/images/activationFunctions.png>\nConsider 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.\n![](../images/body-4d0b9997343e606cb08f.png)\nIf 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.\n![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)\nSource: [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)\nOne 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\".\nIn summary, a thorough understanding of backpropagation can be very beneficial. It's a cornerstone in developing effective neural network models and troubleshooting training problems.\n_(Unless otherwise noted, all images are by the author)_\n* * *\nIf 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.\nOther posts in this series:\n  * [Courage to Learn ML: Demystifying L1 & L2 Regularization (part 1)](https://towardsdatascience.com/understanding-l1-l2-regularization-part-1-9c7affe6f920)\n  * [Courage to Learn ML: Decoding Likelihood, MLE, and MAP](https://towardsdatascience.com/courage-to-learn-ml-decoding-likelihood-mle-and-map-65218b2c2b99)\n  * [Courage to Learn ML: A Deeper Dive into F1, Recall, Precision, and ROC Curves](https://medium.com/p/d5c0a46e5eb7)\n  * [Courage to Learn ML: An In-Depth Guide to the Most Common Loss Functions](https://medium.com/p/84a6b07cca17)\n  * [Courage to Learn ML: A Detailed Exploration of Gradient Descent and Popular Optimizers](https://medium.com/p/022ecf97be7d)\n\n\n* * *\n_**If you liked the article, you can find me on**_[ _**LinkedIn**_](https://www.linkedin.com/in/amyma101/) _**.**_\n## **Reference:**\n<https://machinelearningmastery.com/implement-backpropagation-algorithm-scratch-python/>\nPlease accept cookies to access this content\nPlease accept cookies to access this content\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](../images/body-bf30693e05bb856f0cb2.png)\nWritten By\n## [Amy Ma](https://towardsdatascience.com/author/amyma101/)\n[See all from Amy Ma](https://towardsdatascience.com/author/amyma101/)\n[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/)\nShare This Article\n  * [](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)\n  * [](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)\n  * [](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)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/010.jpg)](https://towardsdatascience.com/this-months-machine-learning-lessons-learned/)\n## [The Machine Learning Lessons I’ve Learned This Month](https://towardsdatascience.com/this-months-machine-learning-lessons-learned/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nAugust 2025: logging, lab notebooks, overnight runs\n[Pascal Janetzky](https://towardsdatascience.com/author/pascaljanetzky/)\nAugust 31, 20254 min read\n  * [![](../images/011.jpg)](https://towardsdatascience.com/weak-supervision-with-snorkel-for-multilabel-classification-tasks-c7af4990ea45/)\n## [Weak Supervision: Labeling Your Data Without Actually Labeling It 🤔](https://towardsdatascience.com/weak-supervision-with-snorkel-for-multilabel-classification-tasks-c7af4990ea45/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nLabel your data programmatically!\n[Albers Uzila](https://towardsdatascience.com/author/dwiuzila/)\nMay 23, 20223 min read\n  * [![](../images/012.jpg)](https://towardsdatascience.com/pytorch-nans-are-silent-killers-i-built-a-3ms-hook-to-catch-them-at-the-exact-layer/)\n## [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/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nThis 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.\n[Emmimal P Alexander](https://towardsdatascience.com/author/emmimalp.alexander/)\nApril 28, 202610 min read\n  * [![](../images/013.jpeg)](https://towardsdatascience.com/llama-2-vs-llama-3-a-tic-tac-toe-battle-between-models-7301962ca65d/)\n## [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/)\n[Programming](https://towardsdatascience.com/category/programming/)\nMaking a non-scientific benchmark with Python and Llama-CPP\n[Dmitrii Eliuseev](https://towardsdatascience.com/author/dmitryelj/)\nApril 27, 202410 min read\n  * [![](../images/014.png)](https://towardsdatascience.com/learn-to-build-advanced-ai-image-applications-9c98d0f1f930/)\n## [Learn to Build Advanced AI Image Applications](https://towardsdatascience.com/learn-to-build-advanced-ai-image-applications-9c98d0f1f930/)\n[Programming](https://towardsdatascience.com/category/programming/)\nBy building an interior designer in ComfyUI\n[Ida Silfverskiold](https://towardsdatascience.com/author/ilsilfverskiold/)\nJanuary 21, 202521 min read\n  * [![](../images/015.jpeg)](https://towardsdatascience.com/emerging-of-machine-learning-and-deep-learning-ddf8e3e5e85e/)\n## [Emerging of Machine Learning and Deep Learning](https://towardsdatascience.com/emerging-of-machine-learning-and-deep-learning-ddf8e3e5e85e/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nData, Computational resources, Algorithms and Open-sourced frameworks\n[Rukshan Pramoditha](https://towardsdatascience.com/author/rukshanpramoditha/)\nJuly 10, 20214 min read\n  * [![](../images/016.jpg)](https://towardsdatascience.com/deploy-multiple-tensorflow-models-to-one-endpoint-65bea81c3f2f/)\n## [Deploy Multiple TensorFlow Models to One Endpoint](https://towardsdatascience.com/deploy-multiple-tensorflow-models-to-one-endpoint-65bea81c3f2f/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nMulti-Model Endpoints with Amazon SageMaker\n[Ram Vegiraju](https://towardsdatascience.com/author/ram-vegiraju/)\nSeptember 2, 20216 min read\n  * [![](../images/017.png)](https://towardsdatascience.com/random-forest-models-why-are-they-better-than-single-decision-trees-70494c29ccd1/)\n## [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/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA detailed explanation of how random forest machine learning algorithm works, what makes it superior to decision trees, and how you can...\n[Saul Dobilas](https://towardsdatascience.com/author/solclover/)\nFebruary 7, 20219 min read\n  * [![](../images/018.jpeg)](https://towardsdatascience.com/what-makes-a-great-data-analyst-f6577cef81a3/)\n## [What Makes a Great Data Analyst?](https://towardsdatascience.com/what-makes-a-great-data-analyst-f6577cef81a3/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nHint: There's No Exact Answer\n[JB](https://towardsdatascience.com/author/josephburton06/)\nSeptember 4, 20217 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe 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/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](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\")\n  * [ ![](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\")\n  * [ ![](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\")\n  * [ ![](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?\")\n\n\n",
  "metadata": {
    "title": "Courage to Learn ML: Explain Backpropagation from Mathematical Theory to Coding Practice | Towards Data Science",
    "description": "Transforming Backpropagation's Complex Math into Manageable and Easy-to-Learn Bites",
    "keywords": null,
    "author": "Amy Ma",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Courage to Learn ML: Explain Backpropagation from Mathematical Theory to Coding Practice",
    "og:description": "Transforming Backpropagation's Complex Math into Manageable and Easy-to-Learn Bites",
    "og:url": "https://towardsdatascience.com/courage-to-learn-ml-explain-backpropagation-from-mathematical-theory-to-coding-practice-21e670415378/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1ysOFKqc_sLg-CA4gotSdPQ.png",
    "og:image:width": "1024",
    "og:image:height": "1024",
    "og:image:type": "image/png",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Amy Ma",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "20 min read",
    "article:published_time": "2024-01-17T14:27:56.000Z",
    "article:modified_time": "2024-01-17T14:27:56.000Z",
    "article:author": "https://towardsdatascience.com/author/amyma101/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/d09fdca7178e/code/block_000.txt",
      "chars": 208
    },
    {
      "language": "txt",
      "file": "attachments/d09fdca7178e/code/block_001.txt",
      "chars": 332
    },
    {
      "language": "txt",
      "file": "attachments/d09fdca7178e/code/block_002.txt",
      "chars": 417
    },
    {
      "language": "txt",
      "file": "attachments/d09fdca7178e/code/block_003.txt",
      "chars": 389
    },
    {
      "language": "txt",
      "file": "attachments/d09fdca7178e/code/block_004.txt",
      "chars": 428
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:42:14Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:42:14Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:42:14Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:42:14Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/@HungyiLeeNTU",
      "kind": "channel_reference",
      "status": "reference_only"
    },
    {
      "url": "https://www.youtube.com/watch?v=ibJpTrp5mcE",
      "status": "ok",
      "local_path": "attachments/d09fdca7178e/videos/repair-ibJpTrp5mcE.mp4",
      "bytes": 42067481,
      "valid": true,
      "height": 720,
      "width": 960,
      "duration": "1885.761000"
    },
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/amyma101/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tagged/courage-to-learn-ml"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/courage-to-learn-ml-a-detailed-exploration-of-gradient-descent-and-popular-optimizers-022ecf97be7d"
    },
    {
      "type": "internal",
      "href": "http://towardsdatascience.com/tagged/courage-to-learn-ml"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/understanding-l1-l2-regularization-part-1-9c7affe6f920"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/courage-to-learn-ml-decoding-likelihood-mle-and-map-65218b2c2b99"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/deep-dives/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/courage-to-learn-ml/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/this-months-machine-learning-lessons-learned/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/machine-learning/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://machinelearningmastery.com/implement-backpropagation-algorithm-scratch-python/"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-engineer"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-data-scientist"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/machine-learning"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/@HungyiLeeNTU"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/watch?t=1510s&v=ibJpTrp5mcE"
    },
    {
      "type": "external",
      "href": "https://dwaithe.github.io/images/activationFunctions.png"
    },
    {
      "type": "external",
      "href": "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"
    },
    {
      "type": "external",
      "href": "https://medium.com/p/d5c0a46e5eb7"
    },
    {
      "type": "external",
      "href": "https://medium.com/p/84a6b07cca17"
    },
    {
      "type": "external",
      "href": "https://medium.com/p/022ecf97be7d"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/in/amyma101/"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=Courage+to+Learn+ML%3A+Explain+Backpropagation+from+Mathematical+Theory+to+Coding+Practice&u=https%3A%2F%2Ftowardsdatascience.com%2Fcourage-to-learn-ml-explain-backpropagation-from-mathematical-theory-to-coding-practice-21e670415378%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=Courage+to+Learn+ML%3A+Explain+Backpropagation+from+Mathematical+Theory+to+Coding+Practice&url=https%3A%2F%2Ftowardsdatascience.com%2Fcourage-to-learn-ml-explain-backpropagation-from-mathematical-theory-to-coding-practice-21e670415378%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=Courage+to+Learn+ML%3A+Explain+Backpropagation+from+Mathematical+Theory+to+Coding+Practice&url=https%3A%2F%2Ftowardsdatascience.com%2Fcourage-to-learn-ml-explain-backpropagation-from-mathematical-theory-to-coding-practice-21e670415378%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    },
    {
      "type": "external",
      "href": "https://www.threads.net/@towardsdatascience"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:25:29Z",
  "source_url": "https://towardsdatascience.com/courage-to-learn-ml-explain-backpropagation-from-mathematical-theory-to-coding-practice-21e670415378/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [
    {
      "local_path": "attachments/d09fdca7178e/videos/repair-ibJpTrp5mcE.mp4",
      "bytes": 42067481,
      "valid": true,
      "height": 720,
      "width": 960,
      "duration": "1885.761000",
      "status": "ok"
    }
  ],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe 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.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe 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\nNecessaryAlways Active\nNecessary 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.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis 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.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress 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.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis 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.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo 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. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes 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.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe 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.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical 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.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot 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).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot 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.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle 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.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance 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.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement 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.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter 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.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter 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.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube 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.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[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/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\n# Courage to Learn ML: Explain Backpropagation from Mathematical Theory to Coding Practice\nTransforming Backpropagation's Complex Math into Manageable and Easy-to-Learn Bites\n[Amy Ma](https://towardsdatascience.com/author/amyma101/)\nJanuary 17, 202420 min read\n![Image created by the author using ChatGPT.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1ysOFKqc_sLg-CA4gotSdPQ.png)\nImage created by the author using ChatGPT.\nWelcome 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.\nThis 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.\nAs always, here's a list of the topics we'll be exploring today:\nLearn 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.\n  * Understanding backpropagation and its connection to gradient Descent\n  * Exploring the preference for depth over width in DNNs and the rarity of shallow, wide networks.\n  * What is the chain rule?\n  * Breaking down backpropagation calculation into 3 components and examining each thoroughly. Why is it called **back** propagation?\n  * Understand backpropagation through straightforward Python code\n  * Gradient vanishing and common preference in activation functions\n\n\n* * *\nLet's start with the fundamental why -\n## What is backpropagation and how is it related to gradient descent?\nGradient 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.\nHowever, 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.\nThis 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.\n## 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?\nThis 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.\nDeep 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.\nShallow 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.\nTo 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.\n## Now, let's explore backpropagation in detail and utilize the code snippets as a resource to deepen our understanding of the concept.\n> 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).\nThe 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.\nConsider 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.\n![We will study backpropagation based on this network. Source: https://www.youtube.com/watch?v=ibJpTrp5mcE&amp;t=1510s](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1ih1pVy1rafohhMVqnipXpQ.png)\nWe 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)\n> 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\nTo 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:\n## What is the chain rule?\nThe 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:\n  * 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\n\n\n![Image created by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1EEow2KM2gZVsgmUpgorVxg.png)\nImage created by the author.\n  * 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).\n\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1flLtJVlbmq6esYdWzeYrQQ.png)\nTo 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.\n![Imagine derivatives as streams of water in a landscape. Image created by the author using ChatGPT.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1bPMuv9FVccyjA4Xz_QOfpA.png)\nImagine derivatives as streams of water in a landscape. Image created by the author using ChatGPT.\n> 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.\n![This image shows a simple but incorrect way to understand the chain rule. Image created by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1kYu70e-6sqKJTHH6qx3P-w.png)\nThis image shows a simple but incorrect way to understand the chain rule. Image created by the author.\n## How is the chain rule applied to our calculation of ∂L(θ)/∂w1?\nReturning 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.\n![Image by source https://www.youtube.com/watch?v=ibJpTrp5mcE&amp;t=1510s, annotated by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1cdfT5Ovsu0p2uaUABd7I5g.png)\nImage by source [https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s](https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s), annotated by the author.\nThis stream flow analogy helps us reinterpret the partial derivative of the loss with respect to the first layer's weights (∂L(θ)/∂w1) more intuitively.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1CHnfOnhMNhDUMQ8gqKGQcQ.png)\nWe can then dissect ∂L(θ)/∂w1, representing the general partial derivative of loss with respect to weight, into three parts using the chain rule:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1pJZ3W_fS2hxJINVUpkfwew.png)\n  * 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.\n  * 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.\n  * 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.\n\n\nAfter 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:\n## 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?\n∂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.\n![Image by source https://www.youtube.com/watch?v=ibJpTrp5mcE&amp;t=1510s, annotated by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/18WKyfh5TuNLoktLaYXwkIQ.png)\nImage by source [https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s](https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s), annotated by the author.\nTo 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.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1EUZzjhsvA2LWGNW6kbyDBQ.png)\nIf 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.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1Qk2L2FuZjvdWsBKshfngkg.png)\nIn 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.\n## 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?\nThe 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.\nAs 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.\nCalculating _σ_ ′(_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.\n**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.\n## 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'?\nI'm glad you noticed that. Let's recap our discussion so far:\nWe'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.\nNow, 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.\n![Imagine the entire neural network as a cake factory&#039;s production line. Image created by the author using ChatGPT.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1esYFicWk5120EMJA1SdO7Q.png)\nImagine the entire neural network as a cake factory's production line. Image created by the author using ChatGPT.\nIn 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.\n![Image by source https://www.youtube.com/watch?v=ibJpTrp5mcE&amp;t=1510s, annotated by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1-ieQvGgzBhHaNLeqRzWfwA.png)\nImage by source [https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s](https://www.youtube.com/watch?v=ibJpTrp5mcE&t=1510s), annotated by the author.\nThis 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.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1GJl3lp_Z_aiGTv49WD15hw.png)\nGiven that\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1H77mBza6HX3D6ErSaqWqwA.png)\nWe combine these with the activation function derivative ∂a/∂z to get\n![This is key to understanding why the process is named as backpropagation.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1OEi4VE3vq8fLXl4TuVsyKw.png)\nThis is key to understanding why the process is named as backpropagation.\nThis 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.\nTo 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.\n## 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?\nLet'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.\n  * 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\n\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1_twCfQEb4Q7cmb7UZOXkUg.png)\n  * 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).\n\n\n## 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?\nYou 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.\nWhen 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.\nMathematically, for batch size n, the gradient of loss L with respect to weight w1 is calculated as\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1tRqkCW-0cY4pTuW44cYhfg.png)\nHere 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.\nAlright, 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:\n## Based on our discussion, how to combine these elements to construct the backpropagation calculation? How to use our insights to decode this code snippet?\nLet'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/) _._\n**Define activation functions and their derivatives**.\nThe 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.\npython\n\n```\n# Transfer neuron activation\ndef transfer(activation):\n  return 1.0 / (1.0 + exp(-activation))\n\n# Calculate the derivative of an neuron output\ndef transfer_derivative(output):\n return output * (1.0 - output)\n```\n\n###  **Calculate ∂** _**L**_**/∂a.**\nThe `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.\n  * **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.\n\n\npython\n\n```\ndef backward_propagate_error(network, expected):\n for i in reversed(range(len(network))):\n  layer = network[i]\n  # calculate the loss forr each layer\n  if i != len(network)-1:\n   ...\n  else: \n      # ∂L/∂a of the output layer  \n   for j in range(len(layer)):\n    neuron = layer[j]\n    errors.append(neuron['output'] - expected[j]) \n```\n\n  * **For hidden layers,** it's calculated based on the weights and `delta` (representing ∂ _L_ /∂z) of the following layer.\n\n\npython\n\n```\n# Backpropagate error and store in neurons\ndef backward_propagate_error(network, expected):\n for i in reversed(range(len(network))):\n  layer = network[i]\n  errors = list()\n  # calculate the loss forr each layer\n  if i != len(network)-1:\n   ...\n        # ∂L/∂a of the hidden layer  \n    for neuron in network[i + 1]: \n     error += (neuron['weights'][j] * neuron['delta']) \n    errors.append(error)\n  else: \n     ... \n```\n\n###  **Calculate ∂** _**L**_**/∂z.**\nHere, we compute ∂ _L_ /∂z as ∂ _L_ /∂a (represented as `errors` in the code)* σ'(z), and store the result as `neuron['delta']`\npython\n\n```\n# Backpropagate error and store in neurons\ndef backward_propagate_error(network, expected):\n  for i in reversed(range(len(network))):\n  layer = network[i]\n  errors = list()\n # calculate the partial derivative of the loss with repsect to the input before activation\n  for j in range(len(layer)):\n   neuron = layer[j] \n   neuron['delta'] = errors[j] * transfer_derivative(neuron['output']) \n```\n\n###  **Calculate ∂** _**L**_**/∂w to adjust weights.**\nFinally, 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`.\npython\n\n```\n# Update network weights with error\ndef update_weights(network, row, l_rate):\n  for i in range(len(network)):\n    inputs = row[:-1]\n    if i != 0:\n      inputs = [neuron['output'] for neuron in network[i - 1]]\n    for neuron in network[i]:\n      for j in range(len(inputs)):\n        neuron['weights'][j] -= l_rate * neuron['delta'] * inputs[j] \n      neuron['weights'][-1] -= l_rate * neuron['delta'] # bias term the input is 1\n```\n\n> 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.\n## You know, backpropagation kind of like the reverse of the forward pass, doesn't it? Is that a fair way to look at it?\nBackpropagation calculation is a akin to the reversed version of forward pass, largely because:\n  * The derivative of activation function mirrors the role of activation function in forward propagation.\n  * 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.\n\n\nHowever, they are still quite different:\n  * **Different starting points.** Forward pass begins with input data X, while backpropagation starts from the loss, making the choice of loss function pivotal.\n  * **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.\n  * **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.\n\n\n## Why is it important for us to understand the intricate details of backpropagation's calculations?\nUnderstanding 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\n## How does backpropagation inform the choice of activation functions?\nRecall 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.\n![Activation Functions and their Derivatives. Source: https://dwaithe.github.io/images/activationFunctions.png](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0w85U8aCXJ9YLGfq8.png)\nActivation Functions and their Derivatives. Source: <https://dwaithe.github.io/images/activationFunctions.png>\nConsider 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.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/11kx2Ui2bGRSqr2K8-ekFoQ.png)\nIf 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.\n![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](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/03WoW6df3qFlEOoAI.png)\nSource: [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)\nOne 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\".\nIn summary, a thorough understanding of backpropagation can be very beneficial. It's a cornerstone in developing effective neural network models and troubleshooting training problems.\n_(Unless otherwise noted, all images are by the author)_\n* * *\nIf 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.\nOther posts in this series:\n  * [Courage to Learn ML: Demystifying L1 & L2 Regularization (part 1)](https://towardsdatascience.com/understanding-l1-l2-regularization-part-1-9c7affe6f920)\n  * [Courage to Learn ML: Decoding Likelihood, MLE, and MAP](https://towardsdatascience.com/courage-to-learn-ml-decoding-likelihood-mle-and-map-65218b2c2b99)\n  * [Courage to Learn ML: A Deeper Dive into F1, Recall, Precision, and ROC Curves](https://medium.com/p/d5c0a46e5eb7)\n  * [Courage to Learn ML: An In-Depth Guide to the Most Common Loss Functions](https://medium.com/p/84a6b07cca17)\n  * [Courage to Learn ML: A Detailed Exploration of Gradient Descent and Popular Optimizers](https://medium.com/p/022ecf97be7d)\n\n\n* * *\n_**If you liked the article, you can find me on**_[ _**LinkedIn**_](https://www.linkedin.com/in/amyma101/) _**.**_\n## **Reference:**\n<https://machinelearningmastery.com/implement-backpropagation-algorithm-scratch-python/>\nPlease accept cookies to access this content\nPlease accept cookies to access this content\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657140029_upufne.png)\nWritten By\n## [Amy Ma](https://towardsdatascience.com/author/amyma101/)\n[See all from Amy Ma](https://towardsdatascience.com/author/amyma101/)\n[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/)\nShare This Article\n  * [](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)\n  * [](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)\n  * [](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)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/08/rajav-shrestha-r-1Jo9UXSvY-unsplash-scaled-1.jpg)](https://towardsdatascience.com/this-months-machine-learning-lessons-learned/)\n## [The Machine Learning Lessons I’ve Learned This Month](https://towardsdatascience.com/this-months-machine-learning-lessons-learned/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nAugust 2025: logging, lab notebooks, overnight runs\n[Pascal Janetzky](https://towardsdatascience.com/author/pascaljanetzky/)\nAugust 31, 20254 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/05/0xpclzt5e_vH7A27M-scaled.jpg)](https://towardsdatascience.com/weak-supervision-with-snorkel-for-multilabel-classification-tasks-c7af4990ea45/)\n## [Weak Supervision: Labeling Your Data Without Actually Labeling It 🤔](https://towardsdatascience.com/weak-supervision-with-snorkel-for-multilabel-classification-tasks-c7af4990ea45/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nLabel your data programmatically!\n[Albers Uzila](https://towardsdatascience.com/author/dwiuzila/)\nMay 23, 20223 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/04/PyTorch-NaNs-Are-Silent-Killers.jpg)](https://towardsdatascience.com/pytorch-nans-are-silent-killers-i-built-a-3ms-hook-to-catch-them-at-the-exact-layer/)\n## [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/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nThis 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.\n[Emmimal P Alexander](https://towardsdatascience.com/author/emmimalp.alexander/)\nApril 28, 202610 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/04/1EJCvNWwx1c1t1Uxlw1iWLw.jpeg)](https://towardsdatascience.com/llama-2-vs-llama-3-a-tic-tac-toe-battle-between-models-7301962ca65d/)\n## [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/)\n[Programming](https://towardsdatascience.com/category/programming/)\nMaking a non-scientific benchmark with Python and Llama-CPP\n[Dmitrii Eliuseev](https://towardsdatascience.com/author/dmitryelj/)\nApril 27, 202410 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/01/18SbeBXFW2TF7kXP06dptGQ.png)](https://towardsdatascience.com/learn-to-build-advanced-ai-image-applications-9c98d0f1f930/)\n## [Learn to Build Advanced AI Image Applications](https://towardsdatascience.com/learn-to-build-advanced-ai-image-applications-9c98d0f1f930/)\n[Programming](https://towardsdatascience.com/category/programming/)\nBy building an interior designer in ComfyUI\n[Ida Silfverskiold](https://towardsdatascience.com/author/ilsilfverskiold/)\nJanuary 21, 202521 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/07/1pqvNJZjF9IK9YLmFJ0H-AQ.jpeg)](https://towardsdatascience.com/emerging-of-machine-learning-and-deep-learning-ddf8e3e5e85e/)\n## [Emerging of Machine Learning and Deep Learning](https://towardsdatascience.com/emerging-of-machine-learning-and-deep-learning-ddf8e3e5e85e/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nData, Computational resources, Algorithms and Open-sourced frameworks\n[Rukshan Pramoditha](https://towardsdatascience.com/author/rukshanpramoditha/)\nJuly 10, 20214 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/09/0dmIwEszF5J5p6nvp.jpg)](https://towardsdatascience.com/deploy-multiple-tensorflow-models-to-one-endpoint-65bea81c3f2f/)\n## [Deploy Multiple TensorFlow Models to One Endpoint](https://towardsdatascience.com/deploy-multiple-tensorflow-models-to-one-endpoint-65bea81c3f2f/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nMulti-Model Endpoints with Amazon SageMaker\n[Ram Vegiraju](https://towardsdatascience.com/author/ram-vegiraju/)\nSeptember 2, 20216 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/02/1VY06u8FKfydzfwv5K2a7OA.png)](https://towardsdatascience.com/random-forest-models-why-are-they-better-than-single-decision-trees-70494c29ccd1/)\n## [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/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA detailed explanation of how random forest machine learning algorithm works, what makes it superior to decision trees, and how you can...\n[Saul Dobilas](https://towardsdatascience.com/author/solclover/)\nFebruary 7, 20219 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/09/1fw2Fg_zC4fTVkTMeHpwoGQ-scaled.jpeg)](https://towardsdatascience.com/what-makes-a-great-data-analyst-f6577cef81a3/)\n## [What Makes a Great Data Analyst?](https://towardsdatascience.com/what-makes-a-great-data-analyst-f6577cef81a3/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nHint: There's No Exact Answer\n[JB](https://towardsdatascience.com/author/josephburton06/)\nSeptember 4, 20217 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe 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/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](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\")\n  * [ ![](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\")\n  * [ ![](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\")\n  * [ ![](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?\")\n\n\n",
  "body_base_path": "attachments/d09fdca7178e/pages/",
  "body_markdown_path": "attachments/d09fdca7178e/pages/archived-body.md",
  "local_html": "attachments/d09fdca7178e/pages/archived-body.html",
  "body_source": "prior_capture"
}