Pytorch如何构建计算图
以下是网站上的pytorch代码示例:Pytorch如何构建计算图,pytorch,computation-graph,Pytorch,Computation Graph,以下是网站上的pytorch代码示例: class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 1 input image channel, 6 output channels, 3x3 square convolution # kernel self.conv1 = nn.Conv2d(1, 6, 3) self.conv2 = nn.Conv2d(6, 16, 3
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 1 input image channel, 6 output channels, 3x3 square convolution
# kernel
self.conv1 = nn.Conv2d(1, 6, 3)
self.conv2 = nn.Conv2d(6, 16, 3)
# an affine operation: y = Wx + b
self.fc1 = nn.Linear(16 * 6 * 6, 120) # 6*6 from image dimension
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
# Max pooling over a (2, 2) window
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
# If the size is a square you can only specify a single number
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
x = x.view(-1, self.num_flat_features(x))
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
在forward函数中,我们只对x应用一系列变换,但从未明确定义哪些对象是该变换的一部分。然而,当计算梯度和更新权重时,Pytorch“神奇地”知道要更新哪些权重以及应该如何计算梯度
这个过程是如何工作的?是否正在进行代码分析,或者我遗漏了什么?是的,在前向传递上有隐式分析。检查结果张量,有一个类似于
grad\u fn=
的链接,允许您展开整个计算图。它是在真正的正向计算过程中构建的,无论您如何定义网络模块,都是以“nn”或“函数”方式面向对象的
你可以利用这个图进行网络分析,就像torchviz在这里所做的那样:我不太确定代码的哪一部分导致了这里的混乱,但是返回的
x
确实有关于层的信息,例如:x=self.fc3(x)
最终得到一个张量,该张量应用了特定的nn.Linear
。如果你print(x)
你甚至可以看到它有一个grad\u fn
属性。很抱歉,这似乎是一个编程问题,所以它是离题的。请读一读。