与前面的类似,只有模型不一样而已,不再赘述。
# 定义模型
input_size, hidden_size, output_size = 784, 256, 10
class Multilayer(torch.nn.Module):
"""
多层感知机模型。
Attributes:
hidden: 隐藏层
output: 输出层
"""
def __init__(self, input_size, hidden_size, output_size):
super(Multilayer, self).__init__()
self.hidden_layer = torch.nn.Linear(input_size, hidden_size)
self.output_layer = torch.nn.Linear(hidden_size, output_size)
def forward(self, x):
a1 = x.view(x.shape[0], -1)
a2 = nn.functional.relu(self.hidden_layer(a1))
a3 = self.output_layer(a2)
return a3