PyTorch 中 nn.functional() 与 nn.sequential() 之间是否存在任何计算效率差异
Are there any computational efficiency differences between nn.functional() Vs nn.sequential() in PyTorch
下面是使用PyTorchnn.functional()模块的前馈网络
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)
两者没有区别。后者可以说更简洁、更容易编写,"objective" 版本的纯(即无状态)函数如 ReLU
和 Sigmoid
的原因是允许它们在像 nn.Sequential
.
下面是使用PyTorchnn.functional()模块的前馈网络
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)
两者没有区别。后者可以说更简洁、更容易编写,"objective" 版本的纯(即无状态)函数如 ReLU
和 Sigmoid
的原因是允许它们在像 nn.Sequential
.