1. 简单全连接神经网络的搭建
class NeuralNet(nn.Module):
def __init__(self, in_features, hidden_features, out_features):
super(NeuralNet, self).__init__()
self.layer1 = nn.Linear(in_features, hidden_features)
self.layer2 = nn.Linear(hidden_features, out_features)
def forward(self, x):
y = self.layer1(x)
y = nn.functional.relu(y)
y = self.layer2(y)
return y
2. 基于时序容器Sequential类来创建神经网络
Sequential — PyTorch 1.11.0 documentation
class NeuralNet(nn.Module):
def __init__(self, in_features, hidden_features, out_features):
super(NeuralNet, self).__init__()
self.layer = nn.Sequential(nn.Linear(in_features, hidden_features),
nn.ReLU(),
nn.Linear(hidden_features, out_features))
def forward(self,x):
y = self.layer(x)
return y
Sequential参数的先后顺序对应模型参数传递的先后顺序