| 15 | |
| 16 | |
| 17 | class Polynomial3(torch.nn.Module): |
| 18 | def __init__(self): |
| 19 | """ |
| 20 | In the constructor we instantiate four parameters and assign them as |
| 21 | member parameters. |
| 22 | """ |
| 23 | super().__init__() |
| 24 | self.a = torch.nn.Parameter(torch.randn(())) |
| 25 | self.b = torch.nn.Parameter(torch.randn(())) |
| 26 | self.c = torch.nn.Parameter(torch.randn(())) |
| 27 | self.d = torch.nn.Parameter(torch.randn(())) |
| 28 | |
| 29 | def forward(self, x): |
| 30 | """ |
| 31 | In the forward function we accept a Tensor of input data and we must return |
| 32 | a Tensor of output data. We can use Modules defined in the constructor as |
| 33 | well as arbitrary operators on Tensors. |
| 34 | """ |
| 35 | return self.a + self.b * x + self.c * x ** 2 + self.d * x ** 3 |
| 36 | |
| 37 | def string(self): |
| 38 | """ |
| 39 | Just like any class in Python, you can also define custom method on PyTorch modules |
| 40 | """ |
| 41 | return f'y = {self.a.item()} + {self.b.item()} x + {self.c.item()} x^2 + {self.d.item()} x^3' |
| 42 | |
| 43 | |
| 44 | # Create Tensors to hold input and outputs. |