Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/main/beginner_source/examples_nn/polynomial_module.py
Views: 713
# -*- coding: utf-8 -*-1"""2PyTorch: Custom nn Modules3--------------------------45A third order polynomial, trained to predict :math:`y=\sin(x)` from :math:`-\pi`6to :math:`\pi` by minimizing squared Euclidean distance.78This implementation defines the model as a custom Module subclass. Whenever you9want a model more complex than a simple sequence of existing Modules you will10need to define your model this way.11"""12import torch13import math141516class Polynomial3(torch.nn.Module):17def __init__(self):18"""19In the constructor we instantiate four parameters and assign them as20member parameters.21"""22super().__init__()23self.a = torch.nn.Parameter(torch.randn(()))24self.b = torch.nn.Parameter(torch.randn(()))25self.c = torch.nn.Parameter(torch.randn(()))26self.d = torch.nn.Parameter(torch.randn(()))2728def forward(self, x):29"""30In the forward function we accept a Tensor of input data and we must return31a Tensor of output data. We can use Modules defined in the constructor as32well as arbitrary operators on Tensors.33"""34return self.a + self.b * x + self.c * x ** 2 + self.d * x ** 33536def string(self):37"""38Just like any class in Python, you can also define custom method on PyTorch modules39"""40return f'y = {self.a.item()} + {self.b.item()} x + {self.c.item()} x^2 + {self.d.item()} x^3'414243# Create Tensors to hold input and outputs.44x = torch.linspace(-math.pi, math.pi, 2000)45y = torch.sin(x)4647# Construct our model by instantiating the class defined above48model = Polynomial3()4950# Construct our loss function and an Optimizer. The call to model.parameters()51# in the SGD constructor will contain the learnable parameters (defined52# with torch.nn.Parameter) which are members of the model.53criterion = torch.nn.MSELoss(reduction='sum')54optimizer = torch.optim.SGD(model.parameters(), lr=1e-6)55for t in range(2000):56# Forward pass: Compute predicted y by passing x to the model57y_pred = model(x)5859# Compute and print loss60loss = criterion(y_pred, y)61if t % 100 == 99:62print(t, loss.item())6364# Zero gradients, perform a backward pass, and update the weights.65optimizer.zero_grad()66loss.backward()67optimizer.step()6869print(f'Result: {model.string()}')707172