【发布时间】:2019-05-13 16:50:23
【问题描述】:
以下是使用 PyTorch 中的 nn.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)
【问题讨论】:
-
@davidvandebunte - 请不要编辑 OP 的代码,尤其是像这样您对代码进行实质性修改的地方(包括缩进和额外的导入)。
-
@DavidMakogon 抱歉,我只是想进行一些小修改以使其可运行。随时恢复。
标签: python-3.x neural-network deep-learning pytorch tensor