PyTorch中的nn.functional()与nn.sequential()之间是否存在任何计算效率差异

时间:2018-12-12 14:42:29

标签: python-3.x neural-network deep-learning pytorch tensor

以下是使用PyTorch中的nn.functional()模块的前馈网络

import torch.nn.functional as F

class newNetwork(nn.Module):
    def __init__(self):
       super().__init__()
        self.fc1 = nn.Linear(784, 128)
        self.fc2 = nn.Linear(128, 64)
        self.fc3 = nn.Linear(64,10)

    def forward(self,x):
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = F.softmax(self.fc3(x))
        return x

model = newNetwork()
model

以下是使用nn.sequential()模块本质上构建相同对象的相同前馈。两者之间有什么区别?我什么时候可以使用一个而不是另一个?

input_size = 784
hidden_sizes = [128, 64]
output_size = 10

建立前馈网络

 model = nn.Sequential(nn.Linear(input_size, hidden_sizes[0]),
                      nn.ReLU(),
                      nn.Linear(hidden_sizes[0], hidden_sizes[1]),
                      nn.ReLU(),
                      nn.Linear(hidden_sizes[1], output_size),
                      nn.Softmax(dim=1))
    print(model)

1 个答案:

答案 0 :(得分:2)

两者之间没有区别。后者可以说更简洁,更容易编写,而纯(即非有状态)函数(如ReLUSigmoid的“目标”版本的原因是允许它们在{{1 }}。