{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Avishek Biswas",
  "title_listed": "PyTorch Explained: From Automatic Differentiation to Training Custom Neural Networks",
  "keywords": "",
  "domain": "机器学习",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/the-basics-of-deep-learning-with-pytorch-in-1-hour/",
  "publish_date": "2025-09-24",
  "corpus_stage": "",
  "notes": "",
  "id": "8035ae22991a",
  "collected_at": "2026-10-02T10:25:03",
  "title": "PyTorch Explained: From Automatic Differentiation to Training Custom Neural Networks | 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[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\n# PyTorch Explained: From Automatic Differentiation to Training Custom Neural Networks\nThe core mechanics of Deep Learning, and how to think the PyTorch way.\n[Avishek Biswas](https://towardsdatascience.com/author/neural.avb/)\nSeptember 24, 202513 min read\n![](../images/000.png)\nLet's learn PyTorch!\nDeep learning is shaping our world as we speak. In fact, it has been slowly revolutionizing software since the early 2010s. In 2025, PyTorch is at the forefront of this revolution, emerging as one of the most important libraries to train neural networks.\nWhether you are working with computer vision, building large language models (LLMs), training a reinforcement learning agent, or experimenting with graph neural networks - your path is going to cross through PyTorch once you enter deep learning city.\n_All images provided in this article have been produced by the author._\nThis guide will provide a whirlwind tour of PyTorch's methodologies and design principles. Over the next hour, we're going to cut through the noise and get straight to the heart of how neural networks are actually trained.\n> This article is about PyTorch's foundational concepts and _how_ to compose and train models — **from simple linear regression all the way to a modern transformer block**.\n> More importantly than the specific code examples presented here, the goal of this article is to teach the main ideas, project-level architectures, and abstractions to work with PyTorch.\n> **In other words, how to think \"the PyTorch way\".**\nBefore we get that far, it is important to understand the basics. PyTorch is built on two core abstractions: tensors and automatic differentiation. Master these two — how tensors store data, and how gradients are used to train neural networks — and the rest of PyTorch will feel natural. Let's discuss Tensors first.\nLearn this step by step with the interactive [Machine Learning](https://roadmap.sh/machine-learning) roadmap.\n## 1. Basics of Tensors\nA tensor is a **multidimensional array** with a dtype, a device, and optional gradient tracking. If you know NumPy arrays, think of tensors as numpy arrays with a few major benefits:\n  * **GPU utilization** : Tensors can perform massively parallel operations in the GPU. Matrix multiplications, additions, and even conditional statements are all supported.\n  * **Computation Graph:** Instead of imagining tensors as an isolated block of data, think of it as a node on a computation graph. (Shown below)\n  * **Automatic Differentiation:** PyTorch automatically calculates partial derivatives of each differentiable operation it performs. We will discuss what this actually means, and why this is a huge deal for training neural networks very shortly.\n\n\n![](../images/001.png)\nA simple computation graph. Pytorch doesn't just calculate the output, but it also stores information about what nodes the data flows through to generate the output. (Source: Author)\n## 2. Automatic Differentiation (Autograd)\nNeural networks in PyTorch construct a dynamic computation graph, and use it to compute gradients automatically. Let's see a simple example to learn this.\nLet us begin with a clean, scalar example so that shapes and values are easy to reason about. The following code computes `z = x^2 + y^3` for scalar x and y, then calls backward to obtain `dz/dx` and `dz/dy`. \npython\n\n```\nx = torch.tensor(2.0, requires_grad=True)\ny = torch.tensor(3.0, requires_grad=True)\n\n# Forward pass: compute z = x^2 + y^3\nz = x**2 + y**3\n\n# Backward pass: compute gradients\nz.backward()\ndz_dx = x.grad # partial derivative wrt x\ndz_dy = y.grad # partial derivative wrt y\n```\n\nWhat is happening:\n  * We created two tensors `x` and `y` with `requires_grad=True`. This tells autograd to track their operations.\n  * The forward computation constructs a small graph for z.\n  * `z.backward()` triggers the reverse-mode autodiff: PyTorch computes the gradients and places them in `x.grad` and `y.grad`.\n\n\nHere is what the results of the above block of code will look like:\n![](../images/body-f5595a7760d68487956c.png)\nIf you did some mental math, here's what the partial derivatives look like for that equation when calculated analytically (spoiler: it works!):\n![](../images/body-9c0333c589987fc2dece.png)\nAnalytical Solution (Source: Author)\n### Chain Rule\n[Chain Rule](https://en.wikipedia.org/wiki/Chain_rule) in calculus is a fundamental formula for differentiating composite functions, which are essentially functions within other functions. In simpler terms, you work from the outside in, taking the derivative of each \"layer\" of the function and multiplying them together.\nLet's take a simple example of how the chain rule works in PyTorch. Let's say you have the following three-step equation:\nEqn 1: `y = x^2`  \nEqn 2: `z = y + 1`  \nEqn 3: `w = z^2`\nBasically, `w` depends on `z`, `z` depends on `y`, `y` depends on `x`. _A basic chain of compositionality._ And let's say you want to find the derivative of `w` with respect to `x`\nThe chain rule in calculus states that to find `dw/dx` we calculate the gradients up the chain of dependencies and multiply them. So:  \n`dw/dx = dw/dz * dz/dy * dy/dx`  \n  \nLet's see how PyTorch does this:\npython\n\n```\n# requires_grad=True tells PyTorch to compute the gradients for this tensor\nx = torch.tensor(2.0, requires_grad=True)\n\n# Define the forward pass\ny = x**2 \nz = y + 1\nw = z**2\n\n# Calculate the gradient\nw.backward()\n\n# print the gradient\nprint(x.grad) # 40\n```\n\nAnd that's it! _It just works_. \nWhat's even more special is that instead of defining x as a scalar like we did above, we can also define it as a multi-dimensional tensor.  \n  \nHere's what happens when we change the first line from initializing a scalar with `torch.tensor(2)` to a 1D-tensor with `torch.tensor([-1, 2])`\n![](../images/body-95a69d211635f5a181a1.png)\nNotice how when x is a vector, Pytorch calculates the gradients for each element of x\nThis is what makes PyTorch _so_ _cool_. You can simultaneously (or parallely) compute gradients for multiple elements _just like that_.\nWhen working on deep learning projects, our inputs are generally multi-dimensional, so PyTorch does a lot of heavy lifting in the background by parallelizing the gradient computation!\n### The Pytorch formula\nAs seen in the previous example, the PyTorch game plan is pretty simple.\n  1. Define the \"forward pass\" of your equation, i.e., how is your _dependent_ variable derived from your _independent_ variables?\n  2. PyTorch automatically computes the backward propagation (provided your equations are differentiable)\n\n\n![](../images/body-b79575a13f590a3fa12b.jpeg)\nWe define the forward function of the computation graph. PyTorch automatically computes the gradients. (Source: Author)\n## 3. Training models\nNow that we understand the basics of auto differentiation, let's see how [linear regression](https://en.wikipedia.org/wiki/Linear_regression) works in PyTorch. The code below constructs a small housing-style dataset with two features (area and age), normalizes them to the range of [-1, 1], and prepares us for some good old-fashioned linear regression.\npython\n\n```\ndf = pd.DataFrame(\n    {\n        \"area\": [120, 180, 150, 210, 105],\n        \"age\": [5, 2, 1, 2, 1],\n        \"price\": [30, 90, 100, 180, 85]\n    }\n)\ndf = normalize(df)\n```\n\nTo do anything with PyTorch, we must first transfer the data into tensors! Notice how the data tensors X and Y do not require gradients because they are constants (i.e., they don't change during training).\nThe weights `W` and `B` are trainable, though. We will update them to _fit_ our dataset. To make it trainable through backpropagation, we need to set `requires_grad=True` for these declarations.\nLook at the code below:\npython\n\n```\n# Note that these are constants, we are not going to update them\nX = torch.tensor(df[[\"area\", \"age\"]].values, dtype=torch.float32)\nY = torch.tensor(df[[\"price\"]].values, dtype=torch.float32)\n\n# These \"require_grad\" So they are trainable weights.\nW = torch.rand(size=(2, 1), requires_grad=True)\nB = torch.rand(1, requires_grad=True)\n```\n\nNext, let's generate a prediction! The forward pass uses the idiomatic matrix multiplication and addition, i.e. `X @ W + B`. \npython\n\n```\n# Generate a prediction\npred = X @ W + B\n```\n\nThe `@` operator basically does matrix multiplication between X and W. The `X @ W + B` model performs a \"[linear transformation](https://en.wikipedia.org/wiki/Linear_map)\" of X. Our goal is to tune the trainable weights W and B so that the prediction is closer to our target ground truth.\nNext, we calculate the error as the mean square error loss. It calculates the distance between our current prediction and the ground truth. If we call `loss.backward()` we will also get the gradients of the trainable variables in the graph (i.e., W and B).\npython\n\n```\nloss.backward()\ndW = W.grad # Tells us \"how much W must change to reduce the loss\"\ndB = B.grad # and \"how much B must change to reduce the loss\"\n\n```\n\n`dW` and `dB` are the gradients of W and B with respect to the loss function. We can apply \"[gradient descent](https://en.wikipedia.org/wiki/Gradient_descent)\" to nudge these trainable parameters in the direction indicated by the gradient.\npython\n\n```\nlr = 0.2 # Learning rate: tells us how much we should update the weights\nwith torch.no_grad():\n    W = W - lr * dW # Updating W with Gradient descent\n    B = B - lr * dB # Updating B with Gradient descent\n\n```\n\nUnderstanding linear regression, loss calculation, and gradient descent are some of the pillars of machine learning, and by extension, deep learning. While updating the weights manually by subtracting the gradients is possible, it is infeasible in practice for deep neural networks with multiple layers of weights. If only there had been a way to automatically update weights without worrying about keeping track like this!\n**Side note**  \nThe above technique of taking small steps in the optimization space to iteratively learn the weights is called Gradient Descent. _Note that there are better ways to learn the optimal W and B for small datasets. Like the_ _**Normal equation**_ _, which gives us an analytical solution that doesn't require any steps or iteration. It is however, computationally expensive for large datasets. For large matrices, the standard approach is to divide the data into minibatches and apply gradient descent individually. This technique is known as_[ _Stochastic Gradient Descent_](https://en.wikipedia.org/wiki/Stochastic_gradient_descent) _(SGD)._\n### Optimizers\nPyTorch optimizers are algorithms (like SGD, Adam, or RMSprop) that adjust the model's weights and biases based on the computed gradients to minimize the loss function.\nLet's check how the above Linear Regression code will look if we replaced the manual weight updates with PyTorch optimizers.\npython\n\n```\nfrom torch.optim import SGD\n... \n\nW = torch.rand(size=(2, 1), requires_grad=True)\nB = torch.rand(1, requires_grad=True)\noptimizer = SGD(params = [W, B], lr=0.1)\nfor step in range(10):\n    pred = X @ W + B # Forward pass\n    loss = ((Y - pred) ** 2).mean() # Calculate loss\n    loss.backward() # Calculate gradients\n    optimizer.step() # Update W and B according to gradients\n    optimizer.zero_grad() # Reset all gradients\n```\n\nThe core loop for training models in PyTorch looks like this:\n  * Forward pass to compute `pred `\n  * Calculate`loss` by finding the error between the prediction (pred) and the ground truth (Y)\n  * Backward pass with `loss.backward()` to populate `W.grad` and `B.grad.`\n  * Step with `optimizer.step()` to update parameters.\n  * Zero gradients with `optimizer.zero_grad()` to avoid accumulation.\n\n\nSGD is a solid baseline for linear regression. As you scale up or face noisier gradients, adaptive optimizers can help. This is where PyTorch's suite of open source optimizers comes into play. This includes adaptive optimizers, like Adam, that use techniques such as momentum and per-parameter learning rates to achieve faster and more stable convergence on these challenging tasks. Here is a flashcard comparing various popular ones:\n![](../images/body-383b8e79ed641a1513e8.png)\nSome common PyTorch optimizers! (Source: Author)\nNot just optimizers, because Torch also provides a host of different loss functions too! Here are some examples:\n![](../images/body-35198fb19ef27157d293.png)\nSome common PyTorch loss functions (Source: Author)\n## 4. Layers and Modules\nJust like we don't need to write our own optimizers, we don't need to declare raw tensors and matrix multiplication logic on our own (for the most part). Pytorch modules have us covered.\nA PyTorch Module is the fundamental building block for all neural networks in PyTorch, acting as a container for layers, learnable parameters, and the logic for how data flows through them. For example, that linear layer we wrote earlier, where we manually declared the weights and biases, we can instead use these lines of code:\npython\n\n```\nlinear_model = nn.Linear(in_size, out_size) # Torch takes care of initializing weights\nprediction = linear_model(input) # Forward pass\n```\n\nWe learned how to make linear models (yay!), but what we really need to learn is how to train larger and deeper neural networks. The simplest type of neural network is the [**multi-layer perceptron**](https://en.wikipedia.org/wiki/Multilayer_perceptron) (MLP). An MLP is basically multiple linear layers with non-linear functions in between.\nCreating MLPs is pretty straightforward in Torch. `nn.Sequential`is a common PyTorch module that is used to _sequentially_ pass the input through multiple layers. Here is the code:\npython\n\n```\n# A 2 layer MLP\nmlp_2_layers = nn.Sequential(\n    nn.Linear(in_size, hidden_units),\n    nn.ReLU(),\n    nn.Linear(hidden_units, out_size)\n)\n\n# A 3 layer MLP\nmlp_3_layers = nn.Sequential(\n    nn.Linear(in_size, hidden_units),\n    nn.ReLU(),\n    nn.Linear(hidden_units, hidden_units),\n    nn.ReLU(),\n    nn.Linear(hidden_units, out_size)\n)\n\n```\n\nMulti-layer perceptrons can learn compositional and non-linear functions! Here is an example of a zig-zag function and how a 2-layer MLP with RELU learns it.\n![](../images/body-b83bf076e4eba4d03a62.gif)\nA 2 layer MLP training on a piecewise linear function (Source: Author)\n## 5. Writing custom networks\nTorch has a vast array of awesome layers and modules that have inspired entire research papers. You can think about these as lego blocks that you can fit into and compose any neural network.\nWant a convolutional network layer for images? Use `nn.Conv2d`.   \nA GRU layer to process sequential tokens? Use `nn.GRU`\nBut most often in research, you would want to write a custom neural network architecture from scratch. The recipe for this process is as follows:\n  1. Subclass from `nn.Module`\n  2. In the `__init__` constructor function, initialize all your layers and weights\n  3. Define a `forward()` where you write the logic of the forward pass\n\n\nHere is an example where we implement the classic [ResNet](https://arxiv.org/abs/1512.03385) architecture:\npython\n\n```\nclass ResNetBlock(nn.Module):\n    def __init__(self, in_channels, out_channels, stride=1, downsample=None):\n        super(ResNetBlock, self).__init__()\n\n        self.conv1 = nn.Conv2d(\n            in_channels,\n            out_channels,\n            kernel_size=3,\n            stride=stride,\n            padding=1,\n            bias=False,\n        )\n        self.bn1 = nn.BatchNorm2d(out_channels)\n        self.conv2 = nn.Conv2d(\n            out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False\n        )\n        self.bn2 = nn.BatchNorm2d(out_channels)\n\n        self.downsample = downsample\n\n    def forward(self, x):\n        residual = x\n\n        out = F.relu(self.bn1(self.conv1(x)))\n        out = self.bn2(self.conv2(out))\n\n        if self.downsample:\n            residual = self.downsample(x)\n\n        out += residual\n        out = F.relu(out)\n\n        return out\n\n```\n\nThat's it! You just initialize your layers and define the forward pass computation graph, and Torch will directly do the backward pass on its own. \n![](../images/body-624f57b4ef261645ec72.png)\nA standard ResNet Block passes embeddings through a short stack of neural network layers (like convolution) and then adds the original embeddings back to the final output\nOf course, you can use your custom layers and modules as parts of a much larger network! For example, here is an example of writing a single transformer block.\npython\n\n```\nclass AttentionLayer(nn.Module):\n    def __init__(self, input_dim, attention_dim=64):\n        super(SimpleAttention, self).__init__()\n\n        # Linear layers for attention computation\n        self.query = nn.Linear(input_dim, attention_dim)\n        self.key = nn.Linear(input_dim, attention_dim)\n        self.value = nn.Linear(input_dim, attention_dim)\n\n        # Scaling factor\n        self.scale = torch.sqrt(torch.FloatTensor([attention_dim]))\n\n    def forward(self, x):\n        # x shape: (batch_size, sequence_length, input_dim)\n        batch_size, seq_len, input_dim = x.size()\n\n        # Compute Q, K, V\n        Q = self.query(x)  # (batch_size, seq_len, attention_dim)\n        K = self.key(x)  # (batch_size, seq_len, attention_dim)\n        V = self.value(x)  # (batch_size, seq_len, attention_dim)\n\n        attention_scores = torch.matmul(Q, K.transpose(-2, -1)) / self.scale # Scaled dot-product attention\n        attention_weights = F.softmax(attention_scores, dim=-1) # Convert attention weights to probabilities \n        attended_output = torch.matmul(attention_weights, V) # Apply attention to values\n\n        return attended_output, attention_weights\n\nclass TransformerBlock(nn.Module):\n    \"\"\"\n    A single transformer block composed of self-attention and a feed-forward network.\n    \"\"\"\n    def __init__(self, embed_dim, ffn_hidden_dim):\n        \"\"\"\n        Args:\n            embed_dim (int): The dimensionality of the model's embeddings.\n            ffn_hidden_dim (int): The dimensionality of the hidden layer in the FFN.\n        \"\"\"\n        super(TransformerBlock, self).__init__()\n        self.attention = SimpleAttention(embed_dim, embed_dim)\n        self.norm1 = nn.LayerNorm(embed_dim)\n        self.norm2 = nn.LayerNorm(embed_dim)\n        \n        self.ffn = nn.Sequential(\n            nn.Linear(embed_dim, ffn_hidden_dim),\n            nn.ReLU(),\n            nn.Linear(ffn_hidden_dim, embed_dim)\n        )\n\n    def forward(self, x):\n        \"\"\"\n        Forward pass for the transformer block.\n        \n        Args:\n            x (torch.Tensor): Input tensor of shape (batch_size, sequence_length, embed_dim).\n            \n        Returns:\n            torch.Tensor: The output tensor of the transformer block.\n        \"\"\"\n        # Self-attention part\n        attended, _ = self.attention(x)\n        # Add & Norm (residual connection)\n        x = self.norm1(attended + x)\n        \n        # Feed-forward part\n        ffn_out = self.ffn(x)\n        # Add & Norm (residual connection)\n        x = self.norm2(ffn_out + x)\n        \n        return x\n\nclass TransformerEncoder(nn.Module):\n    \"\"\"\n    A transformer encoder that stacks multiple TransformerBlocks.\n    \"\"\"\n    def __init__(self, num_layers, embed_dim, ffn_hidden_dim, seq_len, output_dim):\n        \"\"\"\n        Args:\n            num_layers (int): The number of transformer blocks to stack.\n            embed_dim (int): The dimensionality of the model's embeddings.\n            ffn_hidden_dim (int): The dimensionality of the hidden layer in the FFN.\n            seq_len (int): The length of the input sequences.\n            output_dim (int): The dimensionality of the final output (e.g., number of classes).\n        \"\"\"\n        super(TransformerEncoder, self).__init__()\n        \n        # Create a list of transformer blocks\n        self.layers = nn.ModuleList(\n            [TransformerBlock(embed_dim, ffn_hidden_dim) for _ in range(num_layers)]\n        )\n        \n        # Final classification head\n        self.classifier = nn.Linear(embed_dim * seq_len, output_dim)\n\n    def forward(self, x):\n        \"\"\"\n        Forward pass for the full transformer encoder.\n        \n        Args:\n            x (torch.Tensor): Input tensor of shape (batch_size, sequence_length, embed_dim).\n            \n        Returns:\n            torch.Tensor: The final output logits from the classifier.\n        \"\"\"\n        # Pass input through all transformer blocks\n        for layer in self.layers:\n            x = layer(x)\n        \n        # Flatten the output for the classifier\n        x = x.view(x.size(0), -1)\n        \n        # Final classification\n        output = self.classifier(x)\n        return output\n```\n\nNotice how the first module `AttentionLayer` computes [the scaled-dot-product attention](https://arxiv.org/abs/1706.03762). `TransformerBlock` applies layer norms and feedforward networks on top of it. And finally, the `TransformerEncoder` module applies multiple Transformer blocks in a sequence! And just like that, we have a [BERT model](https://arxiv.org/abs/1810.04805) that incorporates multiple stacks of bidirectional attention layers, along with various optimizations such as layer norms and residual connections.\n> **If you are a beginner and this part overwhelms you, this is very much expected!** The cool thing with PyTorch is you get to choose the level of complexity you want to work with depending on your skill level.\n> When you are beginning, you may want to stick to the hundreds of readymade modules Pytorch offers out of the box. You will slowly find the need to branch out and customizing them for your own use-case. And as you write a couple of custom ones on your own, you will grow more and more confident and proficient.\n> The goal of this section was to show you the capabilities and infinite customization you can do by combining modules together. Remember: you write the forward pass, and as long as the full graph is differentiable, Torch will always be able to do the auto-differentiation for you!\n## Next steps\nThe features and concepts covered in this article were handpicked to provide a whirlwind tour of some of Torch's most important capabilities. I have a YouTube video that explains all of these concepts, along with some additional ones like model deployment, dataloaders, distributions, and training methods.\nThat's it for this article! Here are some links where you can learn more about my work. Thanks for the read!\n**Support me on Patreon:**<https://www.patreon.com/NeuralBreakdownwithAVB>\n**My YouTube channel:**  \n<https://www.youtube.com/@avb_fj>\n**Follow me on Twitter:**  \n<https://x.com/neural_avb>\n**Read my articles:**   \n<https://towardsdatascience.com/author/neural-avb/>\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-849620ef9680d77fc51e.jpeg)\nWritten By\n## [Avishek Biswas](https://towardsdatascience.com/author/neural.avb/)\n[See all from Avishek Biswas](https://towardsdatascience.com/author/neural.avb/)\n[Deep Dives](https://towardsdatascience.com/tag/deep-dives/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Neural Network](https://towardsdatascience.com/tag/neural-network/)[Pytorch](https://towardsdatascience.com/tag/pytorch/)[Tensor](https://towardsdatascience.com/tag/tensor/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fthe-basics-of-deep-learning-with-pytorch-in-1-hour%2F&title=PyTorch%20Explained%3A%20From%20Automatic%20Differentiation%20to%20Training%20Custom%20Neural%20Networks)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fthe-basics-of-deep-learning-with-pytorch-in-1-hour%2F&title=PyTorch%20Explained%3A%20From%20Automatic%20Differentiation%20to%20Training%20Custom%20Neural%20Networks)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fthe-basics-of-deep-learning-with-pytorch-in-1-hour%2F&text=PyTorch%20Explained%3A%20From%20Automatic%20Differentiation%20to%20Training%20Custom%20Neural%20Networks)\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/002.png)](https://towardsdatascience.com/a-comprehensive-guide-of-neural-networks-activation-functions-how-when-and-why-54d13506e4b8/)\n## [A Comprehensive Guide of Neural Networks Activation Functions: How, When, and Why?](https://towardsdatascience.com/a-comprehensive-guide-of-neural-networks-activation-functions-how-when-and-why-54d13506e4b8/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nIs the quest of the perfect activation function accessible?\n[Kevin Berlemont, PhD](https://towardsdatascience.com/author/kevin.berlemont/)\nSeptember 22, 20227 min read\n  * [![](../images/003.png)](https://towardsdatascience.com/natural-language-processing-for-absolute-beginners-a195549a3164/)\n## [Natural Language Processing For Absolute Beginners](https://towardsdatascience.com/natural-language-processing-for-absolute-beginners-a195549a3164/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nSolving complex NLP tasks in 10 lines of Python code\n[Dmitrii Eliuseev](https://towardsdatascience.com/author/dmitryelj/)\nSeptember 2, 202310 min read\n  * [![](../images/004.jpeg)](https://towardsdatascience.com/modelling-physiological-signal-estimation-as-a-deep-learning-problem-89dde307c3c5/)\n## [Modelling Physiological Signal Estimation as a Deep Learning Problem](https://towardsdatascience.com/modelling-physiological-signal-estimation-as-a-deep-learning-problem-89dde307c3c5/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nEstimating vital signs like heart rate, breathing rate and SpO2 levels from facial videos using...\n[Anwesh Marwade](https://towardsdatascience.com/author/anweshrm/)\nMay 3, 20219 min read\n  * [![](../images/005.png)](https://towardsdatascience.com/tensorflow-2-0-here-is-what-ive-learned-from-a-i-day-at-google-64a31914610f/)\n## [TensorFlow 2.0 - Here Is What I've Learned From A.I. Day At Google](https://towardsdatascience.com/tensorflow-2-0-here-is-what-ive-learned-from-a-i-day-at-google-64a31914610f/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nFrom Research, Prototype to Production\n[Admond Lee](https://towardsdatascience.com/author/admond1994/)\nJuly 6, 20197 min read\n  * [![](../images/006.png)](https://towardsdatascience.com/linear-regression-from-scratch-e4db8c6d81db/)\n## [Linear Regression & Gradient Descent](https://towardsdatascience.com/linear-regression-from-scratch-e4db8c6d81db/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nLearn about the most fundamental machine learning algorithm\n[Slava Efimov](https://towardsdatascience.com/author/slavahead/)\nNovember 12, 20226 min read\n  * [![](../images/007.png)](https://towardsdatascience.com/shortening-model-deployment-with-tensorflow-d5a11044d0d/)\n## [Shortening model deployment with TensorFlow](https://towardsdatascience.com/shortening-model-deployment-with-tensorflow-d5a11044d0d/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nHow to make ML model deployment and serving easier with TensorFlow\n[Dimitre Oliveira](https://towardsdatascience.com/author/dimitreoliveira/)\nSeptember 28, 202211 min read\n  * [![](../images/008.png)](https://towardsdatascience.com/n-beats-the-first-interpretable-deep-learning-model-that-worked-for-time-series-forecasting-06920daadac2/)\n## [N-BEATS - The First Interpretable Deep Learning Model That Worked for Time Series Forecasting](https://towardsdatascience.com/n-beats-the-first-interpretable-deep-learning-model-that-worked-for-time-series-forecasting-06920daadac2/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nAn easy-to-understand deep dive into how N-BEATS works and how you can use it.\n[Jonte Dancker](https://towardsdatascience.com/author/jodancker/)\nMay 11, 202411 min read\n  * [![](../images/009.jpg)](https://towardsdatascience.com/what-is-amazon-ec2-and-how-to-use-it-2f621210cf4a/)\n## [What is Amazon EC2 and how to use it?](https://towardsdatascience.com/what-is-amazon-ec2-and-how-to-use-it-2f621210cf4a/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nTrain your models with GPU instances on the AWS cloud.\n[NVS Yashwanth](https://towardsdatascience.com/author/nvsyashwanth/)\nOctober 1, 202010 min read\n  * [![](../images/010.jpg)](https://towardsdatascience.com/principal-component-analysis-from-scratch-in-numpy-61843da1f967/)\n## [Principal Component Analysis From Scratch in Numpy](https://towardsdatascience.com/principal-component-analysis-from-scratch-in-numpy-61843da1f967/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nIt started like a times series project. It ended up being a PCA project.\n[Guillermina Sutter Schneider](https://towardsdatascience.com/author/gsutter/)\nDecember 10, 20205 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/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  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "metadata": {
    "title": "PyTorch Explained: From Automatic Differentiation to Training Custom Neural Networks | Towards Data Science",
    "description": "The core mechanics of Deep Learning, and how to think the PyTorch way.",
    "keywords": null,
    "author": "Avishek Biswas",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "PyTorch Explained: From Automatic Differentiation to Training Custom Neural Networks",
    "og:description": "The core mechanics of Deep Learning, and how to think the PyTorch way.",
    "og:url": "https://towardsdatascience.com/the-basics-of-deep-learning-with-pytorch-in-1-hour/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2025/09/Torch_TDS_3.png",
    "og:image:width": "1280",
    "og:image:height": "720",
    "og:image:type": "image/png",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Avishek Biswas",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "13 min read",
    "article:published_time": "2025-09-24T12:20:35.000Z",
    "article:modified_time": "2025-09-24T12:20:35.000Z",
    "article:author": "https://towardsdatascience.com/author/neural.avb/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/8035ae22991a/code/block_000.txt",
      "chars": 272
    },
    {
      "language": "txt",
      "file": "attachments/8035ae22991a/code/block_001.txt",
      "chars": 254
    },
    {
      "language": "txt",
      "file": "attachments/8035ae22991a/code/block_002.txt",
      "chars": 167
    },
    {
      "language": "txt",
      "file": "attachments/8035ae22991a/code/block_003.txt",
      "chars": 332
    },
    {
      "language": "txt",
      "file": "attachments/8035ae22991a/code/block_004.txt",
      "chars": 41
    },
    {
      "language": "txt",
      "file": "attachments/8035ae22991a/code/block_005.txt",
      "chars": 146
    },
    {
      "language": "txt",
      "file": "attachments/8035ae22991a/code/block_006.txt",
      "chars": 206
    },
    {
      "language": "txt",
      "file": "attachments/8035ae22991a/code/block_007.txt",
      "chars": 424
    },
    {
      "language": "txt",
      "file": "attachments/8035ae22991a/code/block_008.txt",
      "chars": 135
    },
    {
      "language": "txt",
      "file": "attachments/8035ae22991a/code/block_009.txt",
      "chars": 338
    },
    {
      "language": "txt",
      "file": "attachments/8035ae22991a/code/block_010.txt",
      "chars": 888
    },
    {
      "language": "txt",
      "file": "attachments/8035ae22991a/code/block_011.txt",
      "chars": 4178
    }
  ],
  "images": [
    {
      "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-20T18:03:21Z"
    },
    {
      "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-20T18:03:21Z"
    },
    {
      "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-20T18:03:22Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:03:22Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    },
    {
      "url": "https://www.youtube.com/@avb_fj",
      "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/deep-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/neural.avb/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/neural-avb/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/deep-dives/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/neural-network/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/pytorch/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/tensor/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/a-comprehensive-guide-of-neural-networks-activation-functions-how-when-and-why-54d13506e4b8/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/kevin.berlemont/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/natural-language-processing-for-absolute-beginners-a195549a3164/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/dmitryelj/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/modelling-physiological-signal-estimation-as-a-deep-learning-problem-89dde307c3c5/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/anweshrm/"
    },
    {
      "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://roadmap.sh/machine-learning"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Chain_rule"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Linear_regression"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Linear_map"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Gradient_descent"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Stochastic_gradient_descent"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Multilayer_perceptron"
    },
    {
      "type": "external",
      "href": "https://arxiv.org/abs/1512.03385"
    },
    {
      "type": "external",
      "href": "https://arxiv.org/abs/1706.03762"
    },
    {
      "type": "external",
      "href": "https://arxiv.org/abs/1810.04805"
    },
    {
      "type": "external",
      "href": "https://www.patreon.com/NeuralBreakdownwithAVB"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/@avb_fj"
    },
    {
      "type": "external",
      "href": "https://x.com/neural_avb"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=PyTorch+Explained%3A+From+Automatic+Differentiation+to+Training+Custom+Neural+Networks&u=https%3A%2F%2Ftowardsdatascience.com%2Fthe-basics-of-deep-learning-with-pytorch-in-1-hour%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=PyTorch+Explained%3A+From+Automatic+Differentiation+to+Training+Custom+Neural+Networks&url=https%3A%2F%2Ftowardsdatascience.com%2Fthe-basics-of-deep-learning-with-pytorch-in-1-hour%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=PyTorch+Explained%3A+From+Automatic+Differentiation+to+Training+Custom+Neural+Networks&url=https%3A%2F%2Ftowardsdatascience.com%2Fthe-basics-of-deep-learning-with-pytorch-in-1-hour%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:31:04Z",
  "source_url": "https://towardsdatascience.com/the-basics-of-deep-learning-with-pytorch-in-1-hour/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "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[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\n# PyTorch Explained: From Automatic Differentiation to Training Custom Neural Networks\nThe core mechanics of Deep Learning, and how to think the PyTorch way.\n[Avishek Biswas](https://towardsdatascience.com/author/neural.avb/)\nSeptember 24, 202513 min read\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/09/Torch_TDS_3.png)\nLet's learn PyTorch!\nDeep learning is shaping our world as we speak. In fact, it has been slowly revolutionizing software since the early 2010s. In 2025, PyTorch is at the forefront of this revolution, emerging as one of the most important libraries to train neural networks.\nWhether you are working with computer vision, building large language models (LLMs), training a reinforcement learning agent, or experimenting with graph neural networks - your path is going to cross through PyTorch once you enter deep learning city.\n_All images provided in this article have been produced by the author._\nThis guide will provide a whirlwind tour of PyTorch's methodologies and design principles. Over the next hour, we're going to cut through the noise and get straight to the heart of how neural networks are actually trained.\n> This article is about PyTorch's foundational concepts and _how_ to compose and train models — **from simple linear regression all the way to a modern transformer block**.\n> More importantly than the specific code examples presented here, the goal of this article is to teach the main ideas, project-level architectures, and abstractions to work with PyTorch.\n> **In other words, how to think \"the PyTorch way\".**\nBefore we get that far, it is important to understand the basics. PyTorch is built on two core abstractions: tensors and automatic differentiation. Master these two — how tensors store data, and how gradients are used to train neural networks — and the rest of PyTorch will feel natural. Let's discuss Tensors first.\nLearn this step by step with the interactive [Machine Learning](https://roadmap.sh/machine-learning) roadmap.\n## 1. Basics of Tensors\nA tensor is a **multidimensional array** with a dtype, a device, and optional gradient tracking. If you know NumPy arrays, think of tensors as numpy arrays with a few major benefits:\n  * **GPU utilization** : Tensors can perform massively parallel operations in the GPU. Matrix multiplications, additions, and even conditional statements are all supported.\n  * **Computation Graph:** Instead of imagining tensors as an isolated block of data, think of it as a node on a computation graph. (Shown below)\n  * **Automatic Differentiation:** PyTorch automatically calculates partial derivatives of each differentiable operation it performs. We will discuss what this actually means, and why this is a huge deal for training neural networks very shortly.\n\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/09/CleanShot-2025-09-20-at-13.11.47@2x-1024x413.png)\nA simple computation graph. Pytorch doesn't just calculate the output, but it also stores information about what nodes the data flows through to generate the output. (Source: Author)\n## 2. Automatic Differentiation (Autograd)\nNeural networks in PyTorch construct a dynamic computation graph, and use it to compute gradients automatically. Let's see a simple example to learn this.\nLet us begin with a clean, scalar example so that shapes and values are easy to reason about. The following code computes `z = x^2 + y^3` for scalar x and y, then calls backward to obtain `dz/dx` and `dz/dy`. \npython\n\n```\nx = torch.tensor(2.0, requires_grad=True)\ny = torch.tensor(3.0, requires_grad=True)\n\n# Forward pass: compute z = x^2 + y^3\nz = x**2 + y**3\n\n# Backward pass: compute gradients\nz.backward()\ndz_dx = x.grad # partial derivative wrt x\ndz_dy = y.grad # partial derivative wrt y\n```\n\nWhat is happening:\n  * We created two tensors `x` and `y` with `requires_grad=True`. This tells autograd to track their operations.\n  * The forward computation constructs a small graph for z.\n  * `z.backward()` triggers the reverse-mode autodiff: PyTorch computes the gradients and places them in `x.grad` and `y.grad`.\n\n\nHere is what the results of the above block of code will look like:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/09/CleanShot-2025-09-19-at-11.21.57@2x-1024x642.png)\nIf you did some mental math, here's what the partial derivatives look like for that equation when calculated analytically (spoiler: it works!):\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/09/CleanShot-2025-09-23-at-03.04.44@2x.png)\nAnalytical Solution (Source: Author)\n### Chain Rule\n[Chain Rule](https://en.wikipedia.org/wiki/Chain_rule) in calculus is a fundamental formula for differentiating composite functions, which are essentially functions within other functions. In simpler terms, you work from the outside in, taking the derivative of each \"layer\" of the function and multiplying them together.\nLet's take a simple example of how the chain rule works in PyTorch. Let's say you have the following three-step equation:\nEqn 1: `y = x^2`  \nEqn 2: `z = y + 1`  \nEqn 3: `w = z^2`\nBasically, `w` depends on `z`, `z` depends on `y`, `y` depends on `x`. _A basic chain of compositionality._ And let's say you want to find the derivative of `w` with respect to `x`\nThe chain rule in calculus states that to find `dw/dx` we calculate the gradients up the chain of dependencies and multiply them. So:  \n`dw/dx = dw/dz * dz/dy * dy/dx`  \n  \nLet's see how PyTorch does this:\npython\n\n```\n# requires_grad=True tells PyTorch to compute the gradients for this tensor\nx = torch.tensor(2.0, requires_grad=True)\n\n# Define the forward pass\ny = x**2 \nz = y + 1\nw = z**2\n\n# Calculate the gradient\nw.backward()\n\n# print the gradient\nprint(x.grad) # 40\n```\n\nAnd that's it! _It just works_. \nWhat's even more special is that instead of defining x as a scalar like we did above, we can also define it as a multi-dimensional tensor.  \n  \nHere's what happens when we change the first line from initializing a scalar with `torch.tensor(2)` to a 1D-tensor with `torch.tensor([-1, 2])`\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/09/CleanShot-2025-09-19-at-12.39.10.png)\nNotice how when x is a vector, Pytorch calculates the gradients for each element of x\nThis is what makes PyTorch _so_ _cool_. You can simultaneously (or parallely) compute gradients for multiple elements _just like that_.\nWhen working on deep learning projects, our inputs are generally multi-dimensional, so PyTorch does a lot of heavy lifting in the background by parallelizing the gradient computation!\n### The Pytorch formula\nAs seen in the previous example, the PyTorch game plan is pretty simple.\n  1. Define the \"forward pass\" of your equation, i.e., how is your _dependent_ variable derived from your _independent_ variables?\n  2. PyTorch automatically computes the backward propagation (provided your equations are differentiable)\n\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/09/Slide2-1024x576.jpeg)\nWe define the forward function of the computation graph. PyTorch automatically computes the gradients. (Source: Author)\n## 3. Training models\nNow that we understand the basics of auto differentiation, let's see how [linear regression](https://en.wikipedia.org/wiki/Linear_regression) works in PyTorch. The code below constructs a small housing-style dataset with two features (area and age), normalizes them to the range of [-1, 1], and prepares us for some good old-fashioned linear regression.\npython\n\n```\ndf = pd.DataFrame(\n    {\n        \"area\": [120, 180, 150, 210, 105],\n        \"age\": [5, 2, 1, 2, 1],\n        \"price\": [30, 90, 100, 180, 85]\n    }\n)\ndf = normalize(df)\n```\n\nTo do anything with PyTorch, we must first transfer the data into tensors! Notice how the data tensors X and Y do not require gradients because they are constants (i.e., they don't change during training).\nThe weights `W` and `B` are trainable, though. We will update them to _fit_ our dataset. To make it trainable through backpropagation, we need to set `requires_grad=True` for these declarations.\nLook at the code below:\npython\n\n```\n# Note that these are constants, we are not going to update them\nX = torch.tensor(df[[\"area\", \"age\"]].values, dtype=torch.float32)\nY = torch.tensor(df[[\"price\"]].values, dtype=torch.float32)\n\n# These \"require_grad\" So they are trainable weights.\nW = torch.rand(size=(2, 1), requires_grad=True)\nB = torch.rand(1, requires_grad=True)\n```\n\nNext, let's generate a prediction! The forward pass uses the idiomatic matrix multiplication and addition, i.e. `X @ W + B`. \npython\n\n```\n# Generate a prediction\npred = X @ W + B\n```\n\nThe `@` operator basically does matrix multiplication between X and W. The `X @ W + B` model performs a \"[linear transformation](https://en.wikipedia.org/wiki/Linear_map)\" of X. Our goal is to tune the trainable weights W and B so that the prediction is closer to our target ground truth.\nNext, we calculate the error as the mean square error loss. It calculates the distance between our current prediction and the ground truth. If we call `loss.backward()` we will also get the gradients of the trainable variables in the graph (i.e., W and B).\npython\n\n```\nloss.backward()\ndW = W.grad # Tells us \"how much W must change to reduce the loss\"\ndB = B.grad # and \"how much B must change to reduce the loss\"\n\n```\n\n`dW` and `dB` are the gradients of W and B with respect to the loss function. We can apply \"[gradient descent](https://en.wikipedia.org/wiki/Gradient_descent)\" to nudge these trainable parameters in the direction indicated by the gradient.\npython\n\n```\nlr = 0.2 # Learning rate: tells us how much we should update the weights\nwith torch.no_grad():\n    W = W - lr * dW # Updating W with Gradient descent\n    B = B - lr * dB # Updating B with Gradient descent\n\n```\n\nUnderstanding linear regression, loss calculation, and gradient descent are some of the pillars of machine learning, and by extension, deep learning. While updating the weights manually by subtracting the gradients is possible, it is infeasible in practice for deep neural networks with multiple layers of weights. If only there had been a way to automatically update weights without worrying about keeping track like this!\n**Side note**  \nThe above technique of taking small steps in the optimization space to iteratively learn the weights is called Gradient Descent. _Note that there are better ways to learn the optimal W and B for small datasets. Like the_ _**Normal equation**_ _, which gives us an analytical solution that doesn't require any steps or iteration. It is however, computationally expensive for large datasets. For large matrices, the standard approach is to divide the data into minibatches and apply gradient descent individually. This technique is known as_[ _Stochastic Gradient Descent_](https://en.wikipedia.org/wiki/Stochastic_gradient_descent) _(SGD)._\n### Optimizers\nPyTorch optimizers are algorithms (like SGD, Adam, or RMSprop) that adjust the model's weights and biases based on the computed gradients to minimize the loss function.\nLet's check how the above Linear Regression code will look if we replaced the manual weight updates with PyTorch optimizers.\npython\n\n```\nfrom torch.optim import SGD\n... \n\nW = torch.rand(size=(2, 1), requires_grad=True)\nB = torch.rand(1, requires_grad=True)\noptimizer = SGD(params = [W, B], lr=0.1)\nfor step in range(10):\n    pred = X @ W + B # Forward pass\n    loss = ((Y - pred) ** 2).mean() # Calculate loss\n    loss.backward() # Calculate gradients\n    optimizer.step() # Update W and B according to gradients\n    optimizer.zero_grad() # Reset all gradients\n```\n\nThe core loop for training models in PyTorch looks like this:\n  * Forward pass to compute `pred `\n  * Calculate`loss` by finding the error between the prediction (pred) and the ground truth (Y)\n  * Backward pass with `loss.backward()` to populate `W.grad` and `B.grad.`\n  * Step with `optimizer.step()` to update parameters.\n  * Zero gradients with `optimizer.zero_grad()` to avoid accumulation.\n\n\nSGD is a solid baseline for linear regression. As you scale up or face noisier gradients, adaptive optimizers can help. This is where PyTorch's suite of open source optimizers comes into play. This includes adaptive optimizers, like Adam, that use techniques such as momentum and per-parameter learning rates to achieve faster and more stable convergence on these challenging tasks. Here is a flashcard comparing various popular ones:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/09/Optimizers-1024x290.png)\nSome common PyTorch optimizers! (Source: Author)\nNot just optimizers, because Torch also provides a host of different loss functions too! Here are some examples:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/09/CleanShot-2025-09-20-at-11.10.30@2x-1024x296.png)\nSome common PyTorch loss functions (Source: Author)\n## 4. Layers and Modules\nJust like we don't need to write our own optimizers, we don't need to declare raw tensors and matrix multiplication logic on our own (for the most part). Pytorch modules have us covered.\nA PyTorch Module is the fundamental building block for all neural networks in PyTorch, acting as a container for layers, learnable parameters, and the logic for how data flows through them. For example, that linear layer we wrote earlier, where we manually declared the weights and biases, we can instead use these lines of code:\npython\n\n```\nlinear_model = nn.Linear(in_size, out_size) # Torch takes care of initializing weights\nprediction = linear_model(input) # Forward pass\n```\n\nWe learned how to make linear models (yay!), but what we really need to learn is how to train larger and deeper neural networks. The simplest type of neural network is the [**multi-layer perceptron**](https://en.wikipedia.org/wiki/Multilayer_perceptron) (MLP). An MLP is basically multiple linear layers with non-linear functions in between.\nCreating MLPs is pretty straightforward in Torch. `nn.Sequential`is a common PyTorch module that is used to _sequentially_ pass the input through multiple layers. Here is the code:\npython\n\n```\n# A 2 layer MLP\nmlp_2_layers = nn.Sequential(\n    nn.Linear(in_size, hidden_units),\n    nn.ReLU(),\n    nn.Linear(hidden_units, out_size)\n)\n\n# A 3 layer MLP\nmlp_3_layers = nn.Sequential(\n    nn.Linear(in_size, hidden_units),\n    nn.ReLU(),\n    nn.Linear(hidden_units, hidden_units),\n    nn.ReLU(),\n    nn.Linear(hidden_units, out_size)\n)\n\n```\n\nMulti-layer perceptrons can learn compositional and non-linear functions! Here is an example of a zig-zag function and how a 2-layer MLP with RELU learns it.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/09/zigzag_mlp_high_res-1.gif)\nA 2 layer MLP training on a piecewise linear function (Source: Author)\n## 5. Writing custom networks\nTorch has a vast array of awesome layers and modules that have inspired entire research papers. You can think about these as lego blocks that you can fit into and compose any neural network.\nWant a convolutional network layer for images? Use `nn.Conv2d`.   \nA GRU layer to process sequential tokens? Use `nn.GRU`\nBut most often in research, you would want to write a custom neural network architecture from scratch. The recipe for this process is as follows:\n  1. Subclass from `nn.Module`\n  2. In the `__init__` constructor function, initialize all your layers and weights\n  3. Define a `forward()` where you write the logic of the forward pass\n\n\nHere is an example where we implement the classic [ResNet](https://arxiv.org/abs/1512.03385) architecture:\npython\n\n```\nclass ResNetBlock(nn.Module):\n    def __init__(self, in_channels, out_channels, stride=1, downsample=None):\n        super(ResNetBlock, self).__init__()\n\n        self.conv1 = nn.Conv2d(\n            in_channels,\n            out_channels,\n            kernel_size=3,\n            stride=stride,\n            padding=1,\n            bias=False,\n        )\n        self.bn1 = nn.BatchNorm2d(out_channels)\n        self.conv2 = nn.Conv2d(\n            out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False\n        )\n        self.bn2 = nn.BatchNorm2d(out_channels)\n\n        self.downsample = downsample\n\n    def forward(self, x):\n        residual = x\n\n        out = F.relu(self.bn1(self.conv1(x)))\n        out = self.bn2(self.conv2(out))\n\n        if self.downsample:\n            residual = self.downsample(x)\n\n        out += residual\n        out = F.relu(out)\n\n        return out\n\n```\n\nThat's it! You just initialize your layers and define the forward pass computation graph, and Torch will directly do the backward pass on its own. \n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/09/CleanShot-2025-09-24-at-10.29.13@2x-1024x304.png)\nA standard ResNet Block passes embeddings through a short stack of neural network layers (like convolution) and then adds the original embeddings back to the final output\nOf course, you can use your custom layers and modules as parts of a much larger network! For example, here is an example of writing a single transformer block.\npython\n\n```\nclass AttentionLayer(nn.Module):\n    def __init__(self, input_dim, attention_dim=64):\n        super(SimpleAttention, self).__init__()\n\n        # Linear layers for attention computation\n        self.query = nn.Linear(input_dim, attention_dim)\n        self.key = nn.Linear(input_dim, attention_dim)\n        self.value = nn.Linear(input_dim, attention_dim)\n\n        # Scaling factor\n        self.scale = torch.sqrt(torch.FloatTensor([attention_dim]))\n\n    def forward(self, x):\n        # x shape: (batch_size, sequence_length, input_dim)\n        batch_size, seq_len, input_dim = x.size()\n\n        # Compute Q, K, V\n        Q = self.query(x)  # (batch_size, seq_len, attention_dim)\n        K = self.key(x)  # (batch_size, seq_len, attention_dim)\n        V = self.value(x)  # (batch_size, seq_len, attention_dim)\n\n        attention_scores = torch.matmul(Q, K.transpose(-2, -1)) / self.scale # Scaled dot-product attention\n        attention_weights = F.softmax(attention_scores, dim=-1) # Convert attention weights to probabilities \n        attended_output = torch.matmul(attention_weights, V) # Apply attention to values\n\n        return attended_output, attention_weights\n\nclass TransformerBlock(nn.Module):\n    \"\"\"\n    A single transformer block composed of self-attention and a feed-forward network.\n    \"\"\"\n    def __init__(self, embed_dim, ffn_hidden_dim):\n        \"\"\"\n        Args:\n            embed_dim (int): The dimensionality of the model's embeddings.\n            ffn_hidden_dim (int): The dimensionality of the hidden layer in the FFN.\n        \"\"\"\n        super(TransformerBlock, self).__init__()\n        self.attention = SimpleAttention(embed_dim, embed_dim)\n        self.norm1 = nn.LayerNorm(embed_dim)\n        self.norm2 = nn.LayerNorm(embed_dim)\n        \n        self.ffn = nn.Sequential(\n            nn.Linear(embed_dim, ffn_hidden_dim),\n            nn.ReLU(),\n            nn.Linear(ffn_hidden_dim, embed_dim)\n        )\n\n    def forward(self, x):\n        \"\"\"\n        Forward pass for the transformer block.\n        \n        Args:\n            x (torch.Tensor): Input tensor of shape (batch_size, sequence_length, embed_dim).\n            \n        Returns:\n            torch.Tensor: The output tensor of the transformer block.\n        \"\"\"\n        # Self-attention part\n        attended, _ = self.attention(x)\n        # Add & Norm (residual connection)\n        x = self.norm1(attended + x)\n        \n        # Feed-forward part\n        ffn_out = self.ffn(x)\n        # Add & Norm (residual connection)\n        x = self.norm2(ffn_out + x)\n        \n        return x\n\nclass TransformerEncoder(nn.Module):\n    \"\"\"\n    A transformer encoder that stacks multiple TransformerBlocks.\n    \"\"\"\n    def __init__(self, num_layers, embed_dim, ffn_hidden_dim, seq_len, output_dim):\n        \"\"\"\n        Args:\n            num_layers (int): The number of transformer blocks to stack.\n            embed_dim (int): The dimensionality of the model's embeddings.\n            ffn_hidden_dim (int): The dimensionality of the hidden layer in the FFN.\n            seq_len (int): The length of the input sequences.\n            output_dim (int): The dimensionality of the final output (e.g., number of classes).\n        \"\"\"\n        super(TransformerEncoder, self).__init__()\n        \n        # Create a list of transformer blocks\n        self.layers = nn.ModuleList(\n            [TransformerBlock(embed_dim, ffn_hidden_dim) for _ in range(num_layers)]\n        )\n        \n        # Final classification head\n        self.classifier = nn.Linear(embed_dim * seq_len, output_dim)\n\n    def forward(self, x):\n        \"\"\"\n        Forward pass for the full transformer encoder.\n        \n        Args:\n            x (torch.Tensor): Input tensor of shape (batch_size, sequence_length, embed_dim).\n            \n        Returns:\n            torch.Tensor: The final output logits from the classifier.\n        \"\"\"\n        # Pass input through all transformer blocks\n        for layer in self.layers:\n            x = layer(x)\n        \n        # Flatten the output for the classifier\n        x = x.view(x.size(0), -1)\n        \n        # Final classification\n        output = self.classifier(x)\n        return output\n```\n\nNotice how the first module `AttentionLayer` computes [the scaled-dot-product attention](https://arxiv.org/abs/1706.03762). `TransformerBlock` applies layer norms and feedforward networks on top of it. And finally, the `TransformerEncoder` module applies multiple Transformer blocks in a sequence! And just like that, we have a [BERT model](https://arxiv.org/abs/1810.04805) that incorporates multiple stacks of bidirectional attention layers, along with various optimizations such as layer norms and residual connections.\n> **If you are a beginner and this part overwhelms you, this is very much expected!** The cool thing with PyTorch is you get to choose the level of complexity you want to work with depending on your skill level.\n> When you are beginning, you may want to stick to the hundreds of readymade modules Pytorch offers out of the box. You will slowly find the need to branch out and customizing them for your own use-case. And as you write a couple of custom ones on your own, you will grow more and more confident and proficient.\n> The goal of this section was to show you the capabilities and infinite customization you can do by combining modules together. Remember: you write the forward pass, and as long as the full graph is differentiable, Torch will always be able to do the auto-differentiation for you!\n## Next steps\nThe features and concepts covered in this article were handpicked to provide a whirlwind tour of some of Torch's most important capabilities. I have a YouTube video that explains all of these concepts, along with some additional ones like model deployment, dataloaders, distributions, and training methods.\nThat's it for this article! Here are some links where you can learn more about my work. Thanks for the read!\n**Support me on Patreon:**<https://www.patreon.com/NeuralBreakdownwithAVB>\n**My YouTube channel:**  \n<https://www.youtube.com/@avb_fj>\n**Follow me on Twitter:**  \n<https://x.com/neural_avb>\n**Read my articles:**   \n<https://towardsdatascience.com/author/neural-avb/>\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/1787657599061_2dgnrr.jpeg)\nWritten By\n## [Avishek Biswas](https://towardsdatascience.com/author/neural.avb/)\n[See all from Avishek Biswas](https://towardsdatascience.com/author/neural.avb/)\n[Deep Dives](https://towardsdatascience.com/tag/deep-dives/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Neural Network](https://towardsdatascience.com/tag/neural-network/)[Pytorch](https://towardsdatascience.com/tag/pytorch/)[Tensor](https://towardsdatascience.com/tag/tensor/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fthe-basics-of-deep-learning-with-pytorch-in-1-hour%2F&title=PyTorch%20Explained%3A%20From%20Automatic%20Differentiation%20to%20Training%20Custom%20Neural%20Networks)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fthe-basics-of-deep-learning-with-pytorch-in-1-hour%2F&title=PyTorch%20Explained%3A%20From%20Automatic%20Differentiation%20to%20Training%20Custom%20Neural%20Networks)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fthe-basics-of-deep-learning-with-pytorch-in-1-hour%2F&text=PyTorch%20Explained%3A%20From%20Automatic%20Differentiation%20to%20Training%20Custom%20Neural%20Networks)\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/2022/09/11JUkLyRhEhSThsKNbAiaHw.png)](https://towardsdatascience.com/a-comprehensive-guide-of-neural-networks-activation-functions-how-when-and-why-54d13506e4b8/)\n## [A Comprehensive Guide of Neural Networks Activation Functions: How, When, and Why?](https://towardsdatascience.com/a-comprehensive-guide-of-neural-networks-activation-functions-how-when-and-why-54d13506e4b8/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nIs the quest of the perfect activation function accessible?\n[Kevin Berlemont, PhD](https://towardsdatascience.com/author/kevin.berlemont/)\nSeptember 22, 20227 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/09/1vemc7wAQOwIdL3yb96jZFg.png)](https://towardsdatascience.com/natural-language-processing-for-absolute-beginners-a195549a3164/)\n## [Natural Language Processing For Absolute Beginners](https://towardsdatascience.com/natural-language-processing-for-absolute-beginners-a195549a3164/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nSolving complex NLP tasks in 10 lines of Python code\n[Dmitrii Eliuseev](https://towardsdatascience.com/author/dmitryelj/)\nSeptember 2, 202310 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/05/1H4mcQqEWDvy83X8vIvZbXg-scaled.jpeg)](https://towardsdatascience.com/modelling-physiological-signal-estimation-as-a-deep-learning-problem-89dde307c3c5/)\n## [Modelling Physiological Signal Estimation as a Deep Learning Problem](https://towardsdatascience.com/modelling-physiological-signal-estimation-as-a-deep-learning-problem-89dde307c3c5/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nEstimating vital signs like heart rate, breathing rate and SpO2 levels from facial videos using...\n[Anwesh Marwade](https://towardsdatascience.com/author/anweshrm/)\nMay 3, 20219 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2019/07/10pI8FeOAScW2TQQdUsRLAA.png)](https://towardsdatascience.com/tensorflow-2-0-here-is-what-ive-learned-from-a-i-day-at-google-64a31914610f/)\n## [TensorFlow 2.0 - Here Is What I've Learned From A.I. Day At Google](https://towardsdatascience.com/tensorflow-2-0-here-is-what-ive-learned-from-a-i-day-at-google-64a31914610f/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nFrom Research, Prototype to Production\n[Admond Lee](https://towardsdatascience.com/author/admond1994/)\nJuly 6, 20197 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/11/1-qgTZFvnfqJ1ce2N5MkLbg.png)](https://towardsdatascience.com/linear-regression-from-scratch-e4db8c6d81db/)\n## [Linear Regression & Gradient Descent](https://towardsdatascience.com/linear-regression-from-scratch-e4db8c6d81db/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nLearn about the most fundamental machine learning algorithm\n[Slava Efimov](https://towardsdatascience.com/author/slavahead/)\nNovember 12, 20226 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/09/1ULjsHtYba4KCXRuCZsDgmg.png)](https://towardsdatascience.com/shortening-model-deployment-with-tensorflow-d5a11044d0d/)\n## [Shortening model deployment with TensorFlow](https://towardsdatascience.com/shortening-model-deployment-with-tensorflow-d5a11044d0d/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nHow to make ML model deployment and serving easier with TensorFlow\n[Dimitre Oliveira](https://towardsdatascience.com/author/dimitreoliveira/)\nSeptember 28, 202211 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1wIZD2NaC2IUu1f2hd6XHGQ.png)](https://towardsdatascience.com/n-beats-the-first-interpretable-deep-learning-model-that-worked-for-time-series-forecasting-06920daadac2/)\n## [N-BEATS - The First Interpretable Deep Learning Model That Worked for Time Series Forecasting](https://towardsdatascience.com/n-beats-the-first-interpretable-deep-learning-model-that-worked-for-time-series-forecasting-06920daadac2/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nAn easy-to-understand deep dive into how N-BEATS works and how you can use it.\n[Jonte Dancker](https://towardsdatascience.com/author/jodancker/)\nMay 11, 202411 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/0QZvOc9yrC_BiTeax-scaled.jpg)](https://towardsdatascience.com/what-is-amazon-ec2-and-how-to-use-it-2f621210cf4a/)\n## [What is Amazon EC2 and how to use it?](https://towardsdatascience.com/what-is-amazon-ec2-and-how-to-use-it-2f621210cf4a/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nTrain your models with GPU instances on the AWS cloud.\n[NVS Yashwanth](https://towardsdatascience.com/author/nvsyashwanth/)\nOctober 1, 202010 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/12/0tDY2dsqsF6DTXFTi-scaled.jpg)](https://towardsdatascience.com/principal-component-analysis-from-scratch-in-numpy-61843da1f967/)\n## [Principal Component Analysis From Scratch in Numpy](https://towardsdatascience.com/principal-component-analysis-from-scratch-in-numpy-61843da1f967/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nIt started like a times series project. It ended up being a PCA project.\n[Guillermina Sutter Schneider](https://towardsdatascience.com/author/gsutter/)\nDecember 10, 20205 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/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  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "body_base_path": "attachments/8035ae22991a/pages/",
  "body_markdown_path": "attachments/8035ae22991a/pages/archived-body.md",
  "local_html": "attachments/8035ae22991a/pages/archived-body.html",
  "body_source": "prior_capture"
}