Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pytorch
GitHub Repository: pytorch/tutorials
Path: blob/main/beginner_source/examples_autograd/polynomial_autograd.py
1384 views
1
"""
2
PyTorch: Tensors and autograd
3
-------------------------------
4
5
A third order polynomial, trained to predict :math:`y=\sin(x)` from :math:`-\pi`
6
to :math:`\pi` by minimizing squared Euclidean distance.
7
8
This implementation computes the forward pass using operations on PyTorch
9
Tensors, and uses PyTorch autograd to compute gradients.
10
11
12
A PyTorch Tensor represents a node in a computational graph. If ``x`` is a
13
Tensor that has ``x.requires_grad=True`` then ``x.grad`` is another Tensor
14
holding the gradient of ``x`` with respect to some scalar value.
15
"""
16
import torch
17
import math
18
19
# We want to be able to train our model on an `accelerator <https://pytorch.org/docs/stable/torch.html#accelerators>`__
20
# such as CUDA, MPS, MTIA, or XPU. If the current accelerator is available, we will use it. Otherwise, we use the CPU.
21
22
dtype = torch.float
23
device = torch.accelerator.current_accelerator().type if torch.accelerator.is_available() else "cpu"
24
print(f"Using {device} device")
25
torch.set_default_device(device)
26
27
# Create Tensors to hold input and outputs.
28
# By default, requires_grad=False, which indicates that we do not need to
29
# compute gradients with respect to these Tensors during the backward pass.
30
x = torch.linspace(-math.pi, math.pi, 2000, dtype=dtype)
31
y = torch.sin(x)
32
33
# Create random Tensors for weights. For a third order polynomial, we need
34
# 4 weights: y = a + b x + c x^2 + d x^3
35
# Setting requires_grad=True indicates that we want to compute gradients with
36
# respect to these Tensors during the backward pass.
37
a = torch.randn((), dtype=dtype, requires_grad=True)
38
b = torch.randn((), dtype=dtype, requires_grad=True)
39
c = torch.randn((), dtype=dtype, requires_grad=True)
40
d = torch.randn((), dtype=dtype, requires_grad=True)
41
42
learning_rate = 1e-6
43
for t in range(2000):
44
# Forward pass: compute predicted y using operations on Tensors.
45
y_pred = a + b * x + c * x ** 2 + d * x ** 3
46
47
# Compute and print loss using operations on Tensors.
48
# Now loss is a Tensor of shape (1,)
49
# loss.item() gets the scalar value held in the loss.
50
loss = (y_pred - y).pow(2).sum()
51
if t % 100 == 99:
52
print(t, loss.item())
53
54
# Use autograd to compute the backward pass. This call will compute the
55
# gradient of loss with respect to all Tensors with requires_grad=True.
56
# After this call a.grad, b.grad. c.grad and d.grad will be Tensors holding
57
# the gradient of the loss with respect to a, b, c, d respectively.
58
loss.backward()
59
60
# Manually update weights using gradient descent. Wrap in torch.no_grad()
61
# because weights have requires_grad=True, but we don't need to track this
62
# in autograd.
63
with torch.no_grad():
64
a -= learning_rate * a.grad
65
b -= learning_rate * b.grad
66
c -= learning_rate * c.grad
67
d -= learning_rate * d.grad
68
69
# Manually zero the gradients after updating weights
70
a.grad = None
71
b.grad = None
72
c.grad = None
73
d.grad = None
74
75
print(f'Result: y = {a.item()} + {b.item()} x + {c.item()} x^2 + {d.item()} x^3')
76
77