与前面的类似,只有模型不一样而已,不再赘述。

    1. # 定义模型
    2. input_size, hidden_size, output_size = 784, 256, 10
    3. class Multilayer(torch.nn.Module):
    4. """
    5. 多层感知机模型。
    6. Attributes:
    7. hidden: 隐藏层
    8. output: 输出层
    9. """
    10. def __init__(self, input_size, hidden_size, output_size):
    11. super(Multilayer, self).__init__()
    12. self.hidden_layer = torch.nn.Linear(input_size, hidden_size)
    13. self.output_layer = torch.nn.Linear(hidden_size, output_size)
    14. def forward(self, x):
    15. a1 = x.view(x.shape[0], -1)
    16. a2 = nn.functional.relu(self.hidden_layer(a1))
    17. a3 = self.output_layer(a2)
    18. return a3

    3.10 多层感知机的简洁实现.py