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



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

import torch.nn as nn
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)

两者之间没有区别。后者可以说更简洁、更容易编写,ReLUSigmoid等纯(即无状态(函数的"客观"版本的原因是允许它们在nn.Sequential等结构中使用。

最新更新