Pytorch 来自';深度强化学习:动手操作';
我正在读马克西姆·拉潘的《深入学习实践》。我在第2章中遇到了这段代码,但有几件事我不明白。有人能解释为什么print(out)的输出给出了三个参数而不是我们输入的单浮点数张量吗。还有,为什么这里需要超级函数?最后,forward接受的x参数是什么?多谢各位Pytorch 来自';深度强化学习:动手操作';,pytorch,Pytorch,我正在读马克西姆·拉潘的《深入学习实践》。我在第2章中遇到了这段代码,但有几件事我不明白。有人能解释为什么print(out)的输出给出了三个参数而不是我们输入的单浮点数张量吗。还有,为什么这里需要超级函数?最后,forward接受的x参数是什么?多谢各位 class OurModule(nn.Module): def __init__(self, num_inputs, num_classes, dropout_prob=0.3): #init super(OurM
class OurModule(nn.Module):
def __init__(self, num_inputs, num_classes, dropout_prob=0.3): #init
super(OurModule, self).__init__() #Call OurModule and pass the net instance (Why is this necessary?)
self.pipe = nn.Sequential( #net.pipe is the nn object now
nn.Linear(num_inputs, 5),
nn.ReLU(),
nn.Linear(5, 20),
nn.ReLU(),
nn.Linear(20, num_classes),
nn.Dropout(p=dropout_prob),
nn.Softmax(dim=1)
)
def forward(self, x): #override the default forward method by passing it our net instance and (return the nn object?). x is the tensor? This is called when 'net' receives a param?
return self.pipe(x)
if __name__ == "__main__":
net = OurModule(num_inputs=2, num_classes=3)
print(net)
v = torch.FloatTensor([[2, 3]])
out = net(v)
print(out) #[2,3] put through the forward method of the nn? Why did we get a third param for the output?
print("Cuda's availability is %s" % torch.cuda.is_available()) #find if gpu is available
if torch.cuda.is_available():
print("Data from cuda: %s" % out.to('cuda'))
OurModule.__mro__
OurModule
定义了一个PyTorchnn.Module
,它接受2
输入(num\u输入
),并产生3
输出(num\u类
)
它包括:
2
输入并产生5
输出的线性
层ReLU
5
输入并产生20
输出的线性层
ReLU
线性
层,它接受20
输入并产生3
(num_类
)输出退出
层Softmax
层2
输入组成的v
,并在调用net(v)
时通过此网络的forward()
方法传递。然后,运行该网络的结果(3
outputs)存储在out
中
在您的示例中,
x
具有v
,torch.FloatTensor([[2,3]])
虽然@JoshVarty提供了一个很好的答案,但我想补充一点
为什么这里需要超级函数
类
OurModule
继承nn.Module
。超级函数意味着您要使用父级(nn.Module
)函数,即init
。您可以参考来查看父类在init
函数中的具体操作。Super是Pythons原生OO的一部分。它将允许多重继承,尽管这里没有用于此目的,但只允许从Pytorch进行单一继承