自定义 手动实现module

  1. class MLP(nn.Module):
  2. def __init__(self):
  3. super().__init__()
  4. self.hidden = nn.Linear(20, 256)
  5. self.out = nn.Linear(256, 10)
  6. def forward(self, x): # 前向计算
  7. return self.out(F.relu(self.hidden(x)))
  8. net = MLP()
  9. # print(net(x))

定义网络

MLP网络

image.png

卷积神经网络

image.png

灵活地建构网络

  1. class FixedhiddenMLP(nn.Module):
  2. def __init__(self):
  3. super().__init__()
  4. self.rand_weight = torch.rand((20, 20), requires_grad=False)
  5. self.liner = nn.Linear(20, 20)
  6. def forward(self, x):
  7. x = self.liner(x)
  8. x = F.relu(torch.mm(x, self.rand_weight) + 1)
  9. x = self.liner(x)
  10. while x.abs().sum() > 1:
  11. x /= 2
  12. return x.sum()