{
  "source_file": "0930",
  "source_platform": "研究机构",
  "author": "PyTorch Tutorials",
  "title_listed": "Learning PyTorch with Examples",
  "keywords": "PyTorch,示例,入门",
  "domain": "机器学习",
  "content_type": "教程",
  "is_paid_flag": "否",
  "url": "https://pytorch.org/tutorials/beginner/pytorch_with_examples.html",
  "publish_date": "持续更新",
  "corpus_stage": "机器学习",
  "notes": "通过示例学 PyTorch",
  "id": "708efb2ef26d",
  "collected_at": "2026-10-02T16:22:17",
  "title": "Learning PyTorch with Examples — PyTorch Tutorials 2.14.0+cu130 documentation",
  "body_markdown": "Learning PyTorch with Examples\n#\nCreated On: Mar 24, 2017 | Last Updated: Sep 29, 2025 | Last Verified: Nov 05, 2024\nAuthor\n:\nJustin Johnson\nNote\nThis is one of our older PyTorch tutorials. You can view our latest\nbeginner content in\nLearn the Basics\n.\nThis tutorial introduces the fundamental concepts of\nPyTorch\nthrough self-contained\nexamples.\nAt its core, PyTorch provides two main features:\nAn n-dimensional Tensor, similar to numpy but can run on GPUs\nAutomatic differentiation for building and training neural networks\nWe will use a problem of fitting\n\\(y=\\sin(x)\\)\nwith a third order polynomial\nas our running example. The network will have four parameters, and will be trained with\ngradient descent to fit random data by minimizing the Euclidean distance\nbetween the network output and the true output.\nNote\nYou can browse the individual examples at the\nend of this page\n.\nTo run the tutorials below, make sure you have the\ntorch\nand\nnumpy\npackages installed.\nTensors\n#\nWarm-up: numpy\n#\nBefore introducing PyTorch, we will first implement the network using\nnumpy.\nNumpy provides an n-dimensional array object, and many functions for\nmanipulating these arrays. Numpy is a generic framework for scientific\ncomputing; it does not know anything about computation graphs, or deep\nlearning, or gradients. However we can easily use numpy to fit a\nthird order polynomial to sine function by manually implementing the forward\nand backward passes through the network using numpy operations:\n# -*- coding: utf-8 -*-\nimport\nnumpy\nas\nnp\nimport\nmath\n# Create random input and output data\nx\n=\nnp\n.\nlinspace\n(\n-\nmath\n.\npi\n,\nmath\n.\npi\n,\n2000\n)\ny\n=\nnp\n.\nsin\n(\nx\n)\n# Randomly initialize weights\na\n=\nnp\n.\nrandom\n.\nrandn\n()\nb\n=\nnp\n.\nrandom\n.\nrandn\n()\nc\n=\nnp\n.\nrandom\n.\nrandn\n()\nd\n=\nnp\n.\nrandom\n.\nrandn\n()\nlearning_rate\n=\n1e-6\nfor\nt\nin\nrange\n(\n2000\n):\n# Forward pass: compute predicted y\n# y = a + b x + c x^2 + d x^3\ny_pred\n=\na\n+\nb\n*\nx\n+\nc\n*\nx\n**\n2\n+\nd\n*\nx\n**\n3\n# Compute and print loss\nloss\n=\nnp\n.\nsquare\n(\ny_pred\n-\ny\n)\n.\nsum\n()\nif\nt\n%\n100\n==\n99\n:\nprint\n(\nt\n,\nloss\n)\n# Backprop to compute gradients of a, b, c, d with respect to loss\ngrad_y_pred\n=\n2.0\n*\n(\ny_pred\n-\ny\n)\ngrad_a\n=\ngrad_y_pred\n.\nsum\n()\ngrad_b\n=\n(\ngrad_y_pred\n*\nx\n)\n.\nsum\n()\ngrad_c\n=\n(\ngrad_y_pred\n*\nx\n**\n2\n)\n.\nsum\n()\ngrad_d\n=\n(\ngrad_y_pred\n*\nx\n**\n3\n)\n.\nsum\n()\n# Update weights\na\n-=\nlearning_rate\n*\ngrad_a\nb\n-=\nlearning_rate\n*\ngrad_b\nc\n-=\nlearning_rate\n*\ngrad_c\nd\n-=\nlearning_rate\n*\ngrad_d\nprint\n(\nf\n'Result: y =\n{\na\n}\n+\n{\nb\n}\nx +\n{\nc\n}\nx^2 +\n{\nd\n}\nx^3'\n)\nPyTorch: Tensors\n#\nNumpy is a great framework, but it cannot utilize GPUs to accelerate its\nnumerical computations. For modern deep neural networks, GPUs often\nprovide speedups of\n50x or greater\n, so\nunfortunately numpy won’t be enough for modern deep learning.\nHere we introduce the most fundamental PyTorch concept: the\nTensor\n.\nA PyTorch Tensor is conceptually identical to a numpy array: a Tensor is\nan n-dimensional array, and PyTorch provides many functions for\noperating on these Tensors. Behind the scenes, Tensors can keep track of\na computational graph and gradients, but they’re also useful as a\ngeneric tool for scientific computing.\nAlso unlike numpy, PyTorch Tensors can utilize GPUs to accelerate\ntheir numeric computations. To run a PyTorch Tensor on GPU, you simply\nneed to specify the correct device.\nHere we use PyTorch Tensors to fit a third order polynomial to sine function.\nLike the numpy example above we need to manually implement the forward\nand backward passes through the network:\n# -*- coding: utf-8 -*-\nimport\ntorch\ndtype\n=\ntorch\n.\nfloat\ndevice\n=\ntorch\n.\ndevice\n(\n\"cpu\"\n)\n# device = torch.device(\"cuda:0\") # Uncomment this to run on GPU\n# Create random input and output data\nx\n=\ntorch\n.\nlinspace\n(\n-\ntorch\n.\npi\n,\ntorch\n.\npi\n,\n2000\n,\ndevice\n=\ndevice\n,\ndtype\n=\ndtype\n)\ny\n=\ntorch\n.\nsin\n(\nx\n)\n# Randomly initialize weights\na\n=\ntorch\n.\nrandn\n((),\ndevice\n=\ndevice\n,\ndtype\n=\ndtype\n)\nb\n=\ntorch\n.\nrandn\n((),\ndevice\n=\ndevice\n,\ndtype\n=\ndtype\n)\nc\n=\ntorch\n.\nrandn\n((),\ndevice\n=\ndevice\n,\ndtype\n=\ndtype\n)\nd\n=\ntorch\n.\nrandn\n((),\ndevice\n=\ndevice\n,\ndtype\n=\ndtype\n)\nlearning_rate\n=\n1e-6\nfor\nt\nin\nrange\n(\n2000\n):\n# Forward pass: compute predicted y\ny_pred\n=\na\n+\nb\n*\nx\n+\nc\n*\nx\n**\n2\n+\nd\n*\nx\n**\n3\n# Compute and print loss\nloss\n=\n(\ny_pred\n-\ny\n)\n.\npow\n(\n2\n)\n.\nsum\n()\n.\nitem\n()\nif\nt\n%\n100\n==\n99\n:\nprint\n(\nt\n,\nloss\n)\n# Backprop to compute gradients of a, b, c, d with respect to loss\ngrad_y_pred\n=\n2.0\n*\n(\ny_pred\n-\ny\n)\ngrad_a\n=\ngrad_y_pred\n.\nsum\n()\ngrad_b\n=\n(\ngrad_y_pred\n*\nx\n)\n.\nsum\n()\ngrad_c\n=\n(\ngrad_y_pred\n*\nx\n**\n2\n)\n.\nsum\n()\ngrad_d\n=\n(\ngrad_y_pred\n*\nx\n**\n3\n)\n.\nsum\n()\n# Update weights using gradient descent\na\n-=\nlearning_rate\n*\ngrad_a\nb\n-=\nlearning_rate\n*\ngrad_b\nc\n-=\nlearning_rate\n*\ngrad_c\nd\n-=\nlearning_rate\n*\ngrad_d\nprint\n(\nf\n'Result: y =\n{\na\n.\nitem\n()\n}\n+\n{\nb\n.\nitem\n()\n}\nx +\n{\nc\n.\nitem\n()\n}\nx^2 +\n{\nd\n.\nitem\n()\n}\nx^3'\n)\nAutograd\n#\nPyTorch: Tensors and autograd\n#\nIn the above examples, we had to manually implement both the forward and\nbackward passes of our neural network. Manually implementing the\nbackward pass is not a big deal for a small two-layer network, but can\nquickly get very hairy for large complex networks.\nThankfully, we can use\nautomatic\ndifferentiation\nto automate the computation of backward passes in neural networks. The\nautograd\npackage in PyTorch provides exactly this functionality.\nWhen using autograd, the forward pass of your network will define a\ncomputational graph\n; nodes in the graph will be Tensors, and edges\nwill be functions that produce output Tensors from input Tensors.\nBackpropagating through this graph then allows you to easily compute\ngradients.\nThis sounds complicated, it’s pretty simple to use in practice. Each Tensor\nrepresents a node in a computational graph. If\nx\nis a Tensor that has\nx.requires_grad=True\nthen\nx.grad\nis another Tensor holding the\ngradient of\nx\nwith respect to some scalar value.\nHere we use PyTorch Tensors and autograd to implement our fitting sine wave\nwith third order polynomial example; now we no longer need to manually\nimplement the backward pass through the network:\nimport\ntorch\nimport\nmath\n# We want to be able to train our model on an `accelerator <https://pytorch.org/docs/stable/torch.html#accelerators>`__\n# such as CUDA, MPS, MTIA, or XPU. If the current accelerator is available, we will use it. Otherwise, we use the CPU.\ndtype\n=\ntorch\n.\nfloat\ndevice\n=\ntorch\n.\naccelerator\n.\ncurrent_accelerator\n()\n.\ntype\nif\ntorch\n.\naccelerator\n.\nis_available\n()\nelse\n\"cpu\"\nprint\n(\nf\n\"Using\n{\ndevice\n}\ndevice\"\n)\ntorch\n.\nset_default_device\n(\ndevice\n)\n# Create Tensors to hold input and outputs.\n# By default, requires_grad=False, which indicates that we do not need to\n# compute gradients with respect to these Tensors during the backward pass.\nx\n=\ntorch\n.\nlinspace\n(\n-\n1\n,\n1\n,\n2000\n,\ndtype\n=\ndtype\n)\ny\n=\ntorch\n.\nexp\n(\nx\n)\n# A Taylor expansion would be 1 + x + (1/2) x**2 + (1/3!) x**3 + ...\n# Create random Tensors for weights. For a third order polynomial, we need\n# 4 weights: y = a + b x + c x^2 + d x^3\n# Setting requires_grad=True indicates that we want to compute gradients with\n# respect to these Tensors during the backward pass.\na\n=\ntorch\n.\nrandn\n((),\ndtype\n=\ndtype\n,\nrequires_grad\n=\nTrue\n)\nb\n=\ntorch\n.\nrandn\n((),\ndtype\n=\ndtype\n,\nrequires_grad\n=\nTrue\n)\nc\n=\ntorch\n.\nrandn\n((),\ndtype\n=\ndtype\n,\nrequires_grad\n=\nTrue\n)\nd\n=\ntorch\n.\nrandn\n((),\ndtype\n=\ndtype\n,\nrequires_grad\n=\nTrue\n)\ninitial_loss\n=\n1.\nlearning_rate\n=\n1e-5\nfor\nt\nin\nrange\n(\n5000\n):\n# Forward pass: compute predicted y using operations on Tensors.\ny_pred\n=\na\n+\nb\n*\nx\n+\nc\n*\nx\n**\n2\n+\nd\n*\nx\n**\n3\n# Compute and print loss using operations on Tensors.\n# Now loss is a Tensor of shape (1,)\n# loss.item() gets the scalar value held in the loss.\nloss\n=\n(\ny_pred\n-\ny\n)\n.\npow\n(\n2\n)\n.\nsum\n()\n# Calculare initial loss, so we can report loss relative to it\nif\nt\n==\n0\n:\ninitial_loss\n=\nloss\n.\nitem\n()\nif\nt\n%\n100\n==\n99\n:\nprint\n(\nf\n'Iteration t =\n{\nt\n:\n4d\n}\nloss(t)/loss(0) =\n{\nround\n(\nloss\n.\nitem\n()\n/\ninitial_loss\n,\n6\n)\n:\n10.6f\n}\na =\n{\na\n.\nitem\n()\n:\n10.6f\n}\nb =\n{\nb\n.\nitem\n()\n:\n10.6f\n}\nc =\n{\nc\n.\nitem\n()\n:\n10.6f\n}\nd =\n{\nd\n.\nitem\n()\n:\n10.6f\n}\n'\n)\n# Use autograd to compute the backward pass. This call will compute the\n# gradient of loss with respect to all Tensors with requires_grad=True.\n# After this call a.grad, b.grad. c.grad and d.grad will be Tensors holding\n# the gradient of the loss with respect to a, b, c, d respectively.\nloss\n.\nbackward\n()\n# Manually update weights using gradient descent. Wrap in torch.no_grad()\n# because weights have requires_grad=True, but we don't need to track this\n# in autograd.\nwith\ntorch\n.\nno_grad\n():\na\n-=\nlearning_rate\n*\na\n.\ngrad\nb\n-=\nlearning_rate\n*\nb\n.\ngrad\nc\n-=\nlearning_rate\n*\nc\n.\ngrad\nd\n-=\nlearning_rate\n*\nd\n.\ngrad\n# Manually zero the gradients after updating weights\na\n.\ngrad\n=\nNone\nb\n.\ngrad\n=\nNone\nc\n.\ngrad\n=\nNone\nd\n.\ngrad\n=\nNone\nprint\n(\nf\n'Result: y =\n{\na\n.\nitem\n()\n}\n+\n{\nb\n.\nitem\n()\n}\nx +\n{\nc\n.\nitem\n()\n}\nx^2 +\n{\nd\n.\nitem\n()\n}\nx^3'\n)\nPyTorch: Defining new autograd functions\n#\nUnder the hood, each primitive autograd operator is really two functions\nthat operate on Tensors. The\nforward\nfunction computes output\nTensors from input Tensors. The\nbackward\nfunction receives the\ngradient of the output Tensors with respect to some scalar value, and\ncomputes the gradient of the input Tensors with respect to that same\nscalar value.\nIn PyTorch we can easily define our own autograd operator by defining a\nsubclass of\ntorch.autograd.Function\nand implementing the\nforward\nand\nbackward\nfunctions. We can then use our new autograd operator by\nconstructing an instance and calling it like a function, passing\nTensors containing input data.\nIn this example we define our model as\n\\(y=a+b P_3(c+dx)\\)\ninstead of\n\\(y=a+bx+cx^2+dx^3\\)\n, where\n\\(P_3(x)=\\frac{1}{2}\\left(5x^3-3x\\right)\\)\nis the\nLegendre polynomial\nof degree three. We write our own custom autograd\nfunction for computing forward and backward of\n\\(P_3\\)\n, and use it to implement\nour model:\nimport\ntorch\nimport\nmath\nclass\nLegendrePolynomial3\n(\ntorch\n.\nautograd\n.\nFunction\n):\n\"\"\"\nWe can implement our own custom autograd Functions by subclassing\ntorch.autograd.Function and implementing the forward and backward passes\nwhich operate on Tensors.\n\"\"\"\n@staticmethod\ndef\nforward\n(\ninput\n):\n\"\"\"\nIn the forward pass we receive a Tensor containing the input and return\na Tensor containing the output. Check out `Extending torch.autograd <https://docs.pytorch.org/docs/stable/notes/extending.html#extending-torch-autograd>`_\nfor further details.\n\"\"\"\nreturn\n0.5\n*\n(\n5\n*\ninput\n**\n3\n-\n3\n*\ninput\n)\n@staticmethod\ndef\nsetup_context\n(\nctx\n,\ninputs\n,\noutput\n):\n\"\"\"\nStore input for use in the backward pass using ``ctx.save_for_backward``.\nOther objects can be stored directly as attributes on the ctx object,\nsuch as ``ctx.my_object = my_object``.\n\"\"\"\ninput\n,\n=\ninputs\nctx\n.\nsave_for_backward\n(\ninput\n)\n@staticmethod\ndef\nbackward\n(\nctx\n,\ngrad_output\n):\n\"\"\"\nIn the backward pass we receive a Tensor containing the gradient of the loss\nwith respect to the output, and we need to compute the gradient of the loss\nwith respect to the input.\n\"\"\"\ninput\n,\n=\nctx\n.\nsaved_tensors\nreturn\ngrad_output\n*\n1.5\n*\n(\n5\n*\ninput\n**\n2\n-\n1\n)\ndtype\n=\ntorch\n.\nfloat\ndevice\n=\n(\ntorch\n.\naccelerator\n.\ncurrent_accelerator\n()\n.\ntype\nif\ntorch\n.\naccelerator\n.\nis_available\n()\nelse\n\"cpu\"\n)\n# Create Tensors to hold input and outputs.\n# By default, requires_grad=False, which indicates that we do not need to\n# compute gradients with respect to these Tensors during the backward pass.\nx\n=\ntorch\n.\nlinspace\n(\n-\nmath\n.\npi\n,\nmath\n.\npi\n,\n2000\n,\ndevice\n=\ndevice\n,\ndtype\n=\ndtype\n)\ny\n=\ntorch\n.\nsin\n(\nx\n)\n# Create random Tensors for weights. For this example, we need\n# 4 weights: y = a + b * P3(c + d * x), these weights need to be initialized\n# not too far from the correct result to ensure convergence.\n# Setting requires_grad=True indicates that we want to compute gradients with\n# respect to these Tensors during the backward pass.\na\n=\ntorch\n.\nfull\n((),\n0.0\n,\ndevice\n=\ndevice\n,\ndtype\n=\ndtype\n,\nrequires_grad\n=\nTrue\n)\nb\n=\ntorch\n.\nfull\n((),\n-\n1.0\n,\ndevice\n=\ndevice\n,\ndtype\n=\ndtype\n,\nrequires_grad\n=\nTrue\n)\nc\n=\ntorch\n.\nfull\n((),\n0.0\n,\ndevice\n=\ndevice\n,\ndtype\n=\ndtype\n,\nrequires_grad\n=\nTrue\n)\nd\n=\ntorch\n.\nfull\n((),\n0.3\n,\ndevice\n=\ndevice\n,\ndtype\n=\ndtype\n,\nrequires_grad\n=\nTrue\n)\nlearning_rate\n=\n5e-6\nfor\nt\nin\nrange\n(\n2000\n):\n# To apply our Function, we use Function.apply method. We alias this as 'P3'.\nP3\n=\nLegendrePolynomial3\n.\napply\n# Forward pass: compute predicted y using operations; we compute\n# P3 using our custom autograd operation.\ny_pred\n=\na\n+\nb\n*\nP3\n(\nc\n+\nd\n*\nx\n)\n# Compute and print loss\nloss\n=\n(\ny_pred\n-\ny\n)\n.\npow\n(\n2\n)\n.\nsum\n()\nif\nt\n%\n100\n==\n99\n:\nprint\n(\nt\n,\nloss\n.\nitem\n())\n# Use autograd to compute the backward pass.\nloss\n.\nbackward\n()\n# Update weights using gradient descent\nwith\ntorch\n.\nno_grad\n():\na\n-=\nlearning_rate\n*\na\n.\ngrad\nb\n-=\nlearning_rate\n*\nb\n.\ngrad\nc\n-=\nlearning_rate\n*\nc\n.\ngrad\nd\n-=\nlearning_rate\n*\nd\n.\ngrad\n# Manually zero the gradients after updating weights\na\n.\ngrad\n=\nNone\nb\n.\ngrad\n=\nNone\nc\n.\ngrad\n=\nNone\nd\n.\ngrad\n=\nNone\nprint\n(\nf\n'Result: y =\n{\na\n.\nitem\n()\n}\n+\n{\nb\n.\nitem\n()\n}\n* P3(\n{\nc\n.\nitem\n()\n}\n+\n{\nd\n.\nitem\n()\n}\nx)'\n)\nnn\nmodule\n#\nPyTorch:\nnn\n#\nComputational graphs and autograd are a very powerful paradigm for\ndefining complex operators and automatically taking derivatives; however\nfor large neural networks raw autograd can be a bit too low-level.\nWhen building neural networks we frequently think of arranging the\ncomputation into\nlayers\n, some of which have\nlearnable parameters\nwhich will be optimized during learning.\nIn TensorFlow, packages like\nKeras\n,\nTensorFlow-Slim\n,\nand\nTFLearn\nprovide higher-level abstractions\nover raw computational graphs that are useful for building neural\nnetworks.\nIn PyTorch, the\nnn\npackage serves this same purpose. The\nnn\npackage defines a set of\nModules\n, which are roughly equivalent to\nneural network layers. A Module receives input Tensors and computes\noutput Tensors, but may also hold internal state such as Tensors\ncontaining learnable parameters. The\nnn\npackage also defines a set\nof useful loss functions that are commonly used when training neural\nnetworks.\nIn this example we use the\nnn\npackage to implement our polynomial model\nnetwork:\n# -*- coding: utf-8 -*-\nimport\ntorch\nimport\nmath\n# Create Tensors to hold input and outputs.\nx\n=\ntorch\n.\nlinspace\n(\n-\nmath\n.\npi\n,\nmath\n.\npi\n,\n2000\n)\ny\n=\ntorch\n.\nsin\n(\nx\n)\n# For this example, the output y is a linear function of (x, x^2, x^3), so\n# we can consider it as a linear layer neural network. Let's prepare the\n# tensor (x, x^2, x^3).\np\n=\ntorch\n.\ntensor\n([\n1\n,\n2\n,\n3\n])\nxx\n=\nx\n.\nunsqueeze\n(\n-\n1\n)\n.\npow\n(\np\n)\n# In the above code, x.unsqueeze(-1) has shape (2000, 1), and p has shape\n# (3,), for this case, broadcasting semantics will apply to obtain a tensor\n# of shape (2000, 3)\n# Use the nn package to define our model as a sequence of layers. nn.Sequential\n# is a Module which contains other Modules, and applies them in sequence to\n# produce its output. The Linear Module computes output from input using a\n# linear function, and holds internal Tensors for its weight and bias.\n# The Flatten layer flatens the output of the linear layer to a 1D tensor,\n# to match the shape of `y`.\nmodel\n=\ntorch\n.\nnn\n.\nSequential\n(\ntorch\n.\nnn\n.\nLinear\n(\n3\n,\n1\n),\ntorch\n.\nnn\n.\nFlatten\n(\n0\n,\n1\n)\n)\n# The nn package also contains definitions of popular loss functions; in this\n# case we will use Mean Squared Error (MSE) as our loss function.\nloss_fn\n=\ntorch\n.\nnn\n.\nMSELoss\n(\nreduction\n=\n'sum'\n)\nlearning_rate\n=\n1e-6\nfor\nt\nin\nrange\n(\n2000\n):\n# Forward pass: compute predicted y by passing x to the model. Module objects\n# override the __call__ operator so you can call them like functions. When\n# doing so you pass a Tensor of input data to the Module and it produces\n# a Tensor of output data.\ny_pred\n=\nmodel\n(\nxx\n)\n# Compute and print loss. We pass Tensors containing the predicted and true\n# values of y, and the loss function returns a Tensor containing the\n# loss.\nloss\n=\nloss_fn\n(\ny_pred\n,\ny\n)\nif\nt\n%\n100\n==\n99\n:\nprint\n(\nt\n,\nloss\n.\nitem\n())\n# Zero the gradients before running the backward pass.\nmodel\n.\nzero_grad\n()\n# Backward pass: compute gradient of the loss with respect to all the learnable\n# parameters of the model. Internally, the parameters of each Module are stored\n# in Tensors with requires_grad=True, so this call will compute gradients for\n# all learnable parameters in the model.\nloss\n.\nbackward\n()\n# Update the weights using gradient descent. Each parameter is a Tensor, so\n# we can access its gradients like we did before.\nwith\ntorch\n.\nno_grad\n():\nfor\nparam\nin\nmodel\n.\nparameters\n():\nparam\n-=\nlearning_rate\n*\nparam\n.\ngrad\n# You can access the first layer of `model` like accessing the first item of a list\nlinear_layer\n=\nmodel\n[\n0\n]\n# For linear layer, its parameters are stored as `weight` and `bias`.\nprint\n(\nf\n'Result: y =\n{\nlinear_layer\n.\nbias\n.\nitem\n()\n}\n+\n{\nlinear_layer\n.\nweight\n[:,\n0\n]\n.\nitem\n()\n}\nx +\n{\nlinear_layer\n.\nweight\n[:,\n1\n]\n.\nitem\n()\n}\nx^2 +\n{\nlinear_layer\n.\nweight\n[:,\n2\n]\n.\nitem\n()\n}\nx^3'\n)\nPyTorch: optim\n#\nUp to this point we have updated the weights of our models by manually\nmutating the Tensors holding learnable parameters with\ntorch.no_grad()\n.\nThis is not a huge burden for simple optimization algorithms like stochastic\ngradient descent, but in practice we often train neural networks using more\nsophisticated optimizers like\nAdaGrad\n,\nRMSProp\n,\nAdam\n, and other.\nThe\noptim\npackage in PyTorch abstracts the idea of an optimization\nalgorithm and provides implementations of commonly used optimization\nalgorithms.\nIn this example we will use the\nnn\npackage to define our model as\nbefore, but we will optimize the model using the\nRMSprop\nalgorithm provided\nby the\noptim\npackage:\n# -*- coding: utf-8 -*-\nimport\ntorch\nimport\nmath\n# Create Tensors to hold input and outputs.\nx\n=\ntorch\n.\nlinspace\n(\n-\nmath\n.\npi\n,\nmath\n.\npi\n,\n2000\n)\ny\n=\ntorch\n.\nsin\n(\nx\n)\n# Prepare the input tensor (x, x^2, x^3).\np\n=\ntorch\n.\ntensor\n([\n1\n,\n2\n,\n3\n])\nxx\n=\nx\n.\nunsqueeze\n(\n-\n1\n)\n.\npow\n(\np\n)\n# Use the nn package to define our model and loss function.\nmodel\n=\ntorch\n.\nnn\n.\nSequential\n(\ntorch\n.\nnn\n.\nLinear\n(\n3\n,\n1\n),\ntorch\n.\nnn\n.\nFlatten\n(\n0\n,\n1\n)\n)\nloss_fn\n=\ntorch\n.\nnn\n.\nMSELoss\n(\nreduction\n=\n'sum'\n)\n# Use the optim package to define an Optimizer that will update the weights of\n# the model for us. Here we will use RMSprop; the optim package contains many other\n# optimization algorithms. The first argument to the RMSprop constructor tells the\n# optimizer which Tensors it should update.\nlearning_rate\n=\n1e-3\noptimizer\n=\ntorch\n.\noptim\n.\nRMSprop\n(\nmodel\n.\nparameters\n(),\nlr\n=\nlearning_rate\n)\nfor\nt\nin\nrange\n(\n2000\n):\n# Forward pass: compute predicted y by passing x to the model.\ny_pred\n=\nmodel\n(\nxx\n)\n# Compute and print loss.\nloss\n=\nloss_fn\n(\ny_pred\n,\ny\n)\nif\nt\n%\n100\n==\n99\n:\nprint\n(\nt\n,\nloss\n.\nitem\n())\n# Before the backward pass, use the optimizer object to zero all of the\n# gradients for the variables it will update (which are the learnable\n# weights of the model). This is because by default, gradients are\n# accumulated in buffers( i.e, not overwritten) whenever .backward()\n# is called. Checkout docs of torch.autograd.backward for more details.\noptimizer\n.\nzero_grad\n()\n# Backward pass: compute gradient of the loss with respect to model\n# parameters\nloss\n.\nbackward\n()\n# Calling the step function on an Optimizer makes an update to its\n# parameters\noptimizer\n.\nstep\n()\nlinear_layer\n=\nmodel\n[\n0\n]\nprint\n(\nf\n'Result: y =\n{\nlinear_layer\n.\nbias\n.\nitem\n()\n}\n+\n{\nlinear_layer\n.\nweight\n[:,\n0\n]\n.\nitem\n()\n}\nx +\n{\nlinear_layer\n.\nweight\n[:,\n1\n]\n.\nitem\n()\n}\nx^2 +\n{\nlinear_layer\n.\nweight\n[:,\n2\n]\n.\nitem\n()\n}\nx^3'\n)\nPyTorch: Custom\nnn\nModules\n#\nSometimes you will want to specify models that are more complex than a\nsequence of existing Modules; for these cases you can define your own\nModules by subclassing\nnn.Module\nand defining a\nforward\nwhich\nreceives input Tensors and produces output Tensors using other\nmodules or other autograd operations on Tensors.\nIn this example we implement our third order polynomial as a custom Module\nsubclass:\n# -*- coding: utf-8 -*-\nimport\ntorch\nimport\nmath\nclass\nPolynomial3\n(\ntorch\n.\nnn\n.\nModule\n):\ndef\n__init__\n(\nself\n):\n\"\"\"\nIn the constructor we instantiate four parameters and assign them as\nmember parameters.\n\"\"\"\nsuper\n()\n.\n__init__\n()\nself\n.\na\n=\ntorch\n.\nnn\n.\nParameter\n(\ntorch\n.\nrandn\n(()))\nself\n.\nb\n=\ntorch\n.\nnn\n.\nParameter\n(\ntorch\n.\nrandn\n(()))\nself\n.\nc\n=\ntorch\n.\nnn\n.\nParameter\n(\ntorch\n.\nrandn\n(()))\nself\n.\nd\n=\ntorch\n.\nnn\n.\nParameter\n(\ntorch\n.\nrandn\n(()))\ndef\nforward\n(\nself\n,\nx\n):\n\"\"\"\nIn the forward function we accept a Tensor of input data and we must return\na Tensor of output data. We can use Modules defined in the constructor as\nwell as arbitrary operators on Tensors.\n\"\"\"\nreturn\nself\n.\na\n+\nself\n.\nb\n*\nx\n+\nself\n.\nc\n*\nx\n**\n2\n+\nself\n.\nd\n*\nx\n**\n3\ndef\nstring\n(\nself\n):\n\"\"\"\nJust like any class in Python, you can also define custom method on PyTorch modules\n\"\"\"\nreturn\nf\n'y =\n{\nself\n.\na\n.\nitem\n()\n}\n+\n{\nself\n.\nb\n.\nitem\n()\n}\nx +\n{\nself\n.\nc\n.\nitem\n()\n}\nx^2 +\n{\nself\n.\nd\n.\nitem\n()\n}\nx^3'\n# Create Tensors to hold input and outputs.\nx\n=\ntorch\n.\nlinspace\n(\n-\nmath\n.\npi\n,\nmath\n.\npi\n,\n2000\n)\ny\n=\ntorch\n.\nsin\n(\nx\n)\n# Construct our model by instantiating the class defined above\nmodel\n=\nPolynomial3\n()\n# Construct our loss function and an Optimizer. The call to model.parameters()\n# in the SGD constructor will contain the learnable parameters (defined\n# with torch.nn.Parameter) which are members of the model.\ncriterion\n=\ntorch\n.\nnn\n.\nMSELoss\n(\nreduction\n=\n'sum'\n)\noptimizer\n=\ntorch\n.\noptim\n.\nSGD\n(\nmodel\n.\nparameters\n(),\nlr\n=\n1e-6\n)\nfor\nt\nin\nrange\n(\n2000\n):\n# Forward pass: Compute predicted y by passing x to the model\ny_pred\n=\nmodel\n(\nx\n)\n# Compute and print loss\nloss\n=\ncriterion\n(\ny_pred\n,\ny\n)\nif\nt\n%\n100\n==\n99\n:\nprint\n(\nt\n,\nloss\n.\nitem\n())\n# Zero gradients, perform a backward pass, and update the weights.\noptimizer\n.\nzero_grad\n()\nloss\n.\nbackward\n()\noptimizer\n.\nstep\n()\nprint\n(\nf\n'Result:\n{\nmodel\n.\nstring\n()\n}\n'\n)\nPyTorch: Control Flow + Weight Sharing\n#\nAs an example of dynamic graphs and weight sharing, we implement a very\nstrange model: a third-fifth order polynomial that on each forward pass\nchooses a random number between 3 and 5 and uses that many orders, reusing\nthe same weights multiple times to compute the fourth and fifth order.\nFor this model we can use normal Python flow control to implement the loop,\nand we can implement weight sharing by simply reusing the same parameter multiple\ntimes when defining the forward pass.\nWe can easily implement this model as a Module subclass:\n# -*- coding: utf-8 -*-\nimport\nrandom\nimport\ntorch\nimport\nmath\nclass\nDynamicNet\n(\ntorch\n.\nnn\n.\nModule\n):\ndef\n__init__\n(\nself\n):\n\"\"\"\nIn the constructor we instantiate five parameters and assign them as members.\n\"\"\"\nsuper\n()\n.\n__init__\n()\nself\n.\na\n=\ntorch\n.\nnn\n.\nParameter\n(\ntorch\n.\nrandn\n(()))\nself\n.\nb\n=\ntorch\n.\nnn\n.\nParameter\n(\ntorch\n.\nrandn\n(()))\nself\n.\nc\n=\ntorch\n.\nnn\n.\nParameter\n(\ntorch\n.\nrandn\n(()))\nself\n.\nd\n=\ntorch\n.\nnn\n.\nParameter\n(\ntorch\n.\nrandn\n(()))\nself\n.\ne\n=\ntorch\n.\nnn\n.\nParameter\n(\ntorch\n.\nrandn\n(()))\ndef\nforward\n(\nself\n,\nx\n):\n\"\"\"\nFor the forward pass of the model, we randomly choose either 4, 5\nand reuse the e parameter to compute the contribution of these orders.\nSince each forward pass builds a dynamic computation graph, we can use normal\nPython control-flow operators like loops or conditional statements when\ndefining the forward pass of the model.\nHere we also see that it is perfectly safe to reuse the same parameter many\ntimes when defining a computational graph.\n\"\"\"\ny\n=\nself\n.\na\n+\nself\n.\nb\n*\nx\n+\nself\n.\nc\n*\nx\n**\n2\n+\nself\n.\nd\n*\nx\n**\n3\nfor\nexp\nin\nrange\n(\n4\n,\nrandom\n.\nrandint\n(\n4\n,\n6\n)):\ny\n=\ny\n+\nself\n.\ne\n*\nx\n**\nexp\nreturn\ny\ndef\nstring\n(\nself\n):\n\"\"\"\nJust like any class in Python, you can also define custom method on PyTorch modules\n\"\"\"\nreturn\nf\n'y =\n{\nself\n.\na\n.\nitem\n()\n}\n+\n{\nself\n.\nb\n.\nitem\n()\n}\nx +\n{\nself\n.\nc\n.\nitem\n()\n}\nx^2 +\n{\nself\n.\nd\n.\nitem\n()\n}\nx^3 +\n{\nself\n.\ne\n.\nitem\n()\n}\nx^4 ? +\n{\nself\n.\ne\n.\nitem\n()\n}\nx^5 ?'\n# Create Tensors to hold input and outputs.\nx\n=\ntorch\n.\nlinspace\n(\n-\nmath\n.\npi\n,\nmath\n.\npi\n,\n2000\n)\ny\n=\ntorch\n.\nsin\n(\nx\n)\n# Construct our model by instantiating the class defined above\nmodel\n=\nDynamicNet\n()\n# Construct our loss function and an Optimizer. Training this strange model with\n# vanilla stochastic gradient descent is tough, so we use momentum\ncriterion\n=\ntorch\n.\nnn\n.\nMSELoss\n(\nreduction\n=\n'sum'\n)\noptimizer\n=\ntorch\n.\noptim\n.\nSGD\n(\nmodel\n.\nparameters\n(),\nlr\n=\n1e-8\n,\nmomentum\n=\n0.9\n)\nfor\nt\nin\nrange\n(\n30000\n):\n# Forward pass: Compute predicted y by passing x to the model\ny_pred\n=\nmodel\n(\nx\n)\n# Compute and print loss\nloss\n=\ncriterion\n(\ny_pred\n,\ny\n)\nif\nt\n%\n2000\n==\n1999\n:\nprint\n(\nt\n,\nloss\n.\nitem\n())\n# Zero gradients, perform a backward pass, and update the weights.\noptimizer\n.\nzero_grad\n()\nloss\n.\nbackward\n()\noptimizer\n.\nstep\n()\nprint\n(\nf\n'Result:\n{\nmodel\n.\nstring\n()\n}\n'\n)\nExamples\n#\nYou can browse the above examples here.\nTensors\n#\nWarm-up: numpy\nPyTorch: Tensors\nAutograd\n#\nPyTorch: Tensors and autograd\nPyTorch: Defining New autograd Functions\nnn\nmodule\n#\nPyTorch: nn\nPyTorch: optim\nPyTorch: Custom nn Modules\nPyTorch: Control Flow + Weight Sharing",
  "metadata": {
    "title": "Learning PyTorch with Examples — PyTorch Tutorials 2.14.0+cu130 documentation",
    "description": null,
    "keywords": null,
    "author": null,
    "og:image": "https://docs.pytorch.org/docs/stable/_static/img/pytorch_seo.png",
    "article:modified_time": "2022-07-20T23:02:43+00:00"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "file": "attachments/708efb2ef26d/code/body-000.txt",
      "chars": 1015,
      "language": "text"
    },
    {
      "file": "attachments/708efb2ef26d/code/body-001.txt",
      "chars": 1276,
      "language": "text"
    },
    {
      "file": "attachments/708efb2ef26d/code/body-002.txt",
      "chars": 2844,
      "language": "text"
    },
    {
      "file": "attachments/708efb2ef26d/code/body-003.txt",
      "chars": 3380,
      "language": "text"
    },
    {
      "file": "attachments/708efb2ef26d/code/body-004.txt",
      "chars": 2822,
      "language": "text"
    },
    {
      "file": "attachments/708efb2ef26d/code/body-005.txt",
      "chars": 1865,
      "language": "text"
    },
    {
      "file": "attachments/708efb2ef26d/code/body-006.txt",
      "chars": 1962,
      "language": "text"
    },
    {
      "file": "attachments/708efb2ef26d/code/body-007.txt",
      "chars": 2405,
      "language": "text"
    }
  ],
  "images": [],
  "audio": [],
  "videos": [],
  "links": [
    {
      "href": "https://github.com/jcjohnson/pytorch-examples",
      "label": "Justin Johnson",
      "type": "a"
    },
    {
      "href": "https://pytorch.org/tutorials/beginner/basics/intro.html",
      "label": "Learn the Basics",
      "type": "a"
    },
    {
      "href": "https://github.com/pytorch/pytorch",
      "label": "PyTorch",
      "type": "a"
    },
    {
      "href": "https://github.com/numpy/numpy",
      "label": "numpy",
      "type": "a"
    },
    {
      "href": "https://github.com/jcjohnson/cnn-benchmarks",
      "label": "50x or greater",
      "type": "a"
    },
    {
      "href": "https://en.wikipedia.org/wiki/Automatic_differentiation",
      "label": "automatic\ndifferentiation",
      "type": "a"
    },
    {
      "href": "https://en.wikipedia.org/wiki/Legendre_polynomials",
      "label": "Legendre polynomial",
      "type": "a"
    },
    {
      "href": "https://github.com/fchollet/keras",
      "label": "Keras",
      "type": "a"
    },
    {
      "href": "https://github.com/google-research/tf-slim",
      "label": "TensorFlow-Slim",
      "type": "a"
    },
    {
      "href": "http://tflearn.org/",
      "label": "TFLearn",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/tutorials/beginner/examples_tensor/polynomial_numpy.html",
      "label": "Warm-up: numpy",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/tutorials/beginner/examples_tensor/polynomial_tensor.html",
      "label": "PyTorch: Tensors",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/tutorials/beginner/examples_autograd/polynomial_autograd.html",
      "label": "PyTorch: Tensors and autograd",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/tutorials/beginner/examples_autograd/polynomial_custom_function.html",
      "label": "PyTorch: Defining New autograd Functions",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/tutorials/beginner/examples_nn/polynomial_nn.html",
      "label": "PyTorch: nn",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/tutorials/beginner/examples_nn/polynomial_optim.html",
      "label": "PyTorch: optim",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/tutorials/beginner/examples_nn/polynomial_module.html",
      "label": "PyTorch: Custom nn Modules",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/tutorials/beginner/examples_nn/dynamic_net.html",
      "label": "PyTorch: Control Flow + Weight Sharing",
      "type": "a"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-14T10:53:55Z",
  "source_url": "https://pytorch.org/tutorials/beginner/pytorch_with_examples.html",
  "papers": [],
  "actual_video_files": [],
  "body_chars": 25206,
  "expected_body_images": 0,
  "discovery_status": "ok",
  "delivery_status": "ok",
  "missing_reason": "",
  "raw_html": "attachments/708efb2ef26d/pages/source.html",
  "local_html": "attachments/708efb2ef26d/pages/article.html",
  "body_base_path": "attachments/708efb2ef26d/pages/",
  "body_markdown_path": "attachments/708efb2ef26d/pages/article.md"
}