PyTorch:自定义nn模块

原文:https://pytorch.org/tutorials/beginner/examples_nn/polynomial_module.html#sphx-glr-beginner-examples-nn-polynomial-module-py

经过训练的三阶多项式,可以通过最小化平方的欧几里得距离来预测y = sin(x)-pipi

此实现将模型定义为自定义Module子类。 每当您想要一个比现有模块的简单序列更复杂的模型时,都需要以这种方式定义模型。

  1. import torch
  2. import math
  3. class Polynomial3(torch.nn.Module):
  4. def __init__(self):
  5. """
  6. In the constructor we instantiate four parameters and assign them as
  7. member parameters.
  8. """
  9. super().__init__()
  10. self.a = torch.nn.Parameter(torch.randn(()))
  11. self.b = torch.nn.Parameter(torch.randn(()))
  12. self.c = torch.nn.Parameter(torch.randn(()))
  13. self.d = torch.nn.Parameter(torch.randn(()))
  14. def forward(self, x):
  15. """
  16. In the forward function we accept a Tensor of input data and we must return
  17. a Tensor of output data. We can use Modules defined in the constructor as
  18. well as arbitrary operators on Tensors.
  19. """
  20. return self.a + self.b * x + self.c * x ** 2 + self.d * x ** 3
  21. def string(self):
  22. """
  23. Just like any class in Python, you can also define custom method on PyTorch modules
  24. """
  25. return f'y = {self.a.item()} + {self.b.item()} x + {self.c.item()} x^2 + {self.d.item()} x^3'
  26. # Create Tensors to hold input and outputs.
  27. x = torch.linspace(-math.pi, math.pi, 2000)
  28. y = torch.sin(x)
  29. # Construct our model by instantiating the class defined above
  30. model = Polynomial3()
  31. # Construct our loss function and an Optimizer. The call to model.parameters()
  32. # in the SGD constructor will contain the learnable parameters of the nn.Linear
  33. # module which is members of the model.
  34. criterion = torch.nn.MSELoss(reduction='sum')
  35. optimizer = torch.optim.SGD(model.parameters(), lr=1e-6)
  36. for t in range(2000):
  37. # Forward pass: Compute predicted y by passing x to the model
  38. y_pred = model(x)
  39. # Compute and print loss
  40. loss = criterion(y_pred, y)
  41. if t % 100 == 99:
  42. print(t, loss.item())
  43. # Zero gradients, perform a backward pass, and update the weights.
  44. optimizer.zero_grad()
  45. loss.backward()
  46. optimizer.step()
  47. print(f'Result: {model.string()}')

脚本的总运行时间:(0 分钟 0.000 秒)

下载 Python 源码:polynomial_module.py

下载 Jupyter 笔记本:polynomial_module.ipynb

由 Sphinx 画廊生成的画廊