Pytorch初学者在这里!考虑以下自定义模块:
class Testme(nn.Module):
def __init__(self):
super(Testme, self).__init__()
def forward(self, x):
return x / t_.max(x).expand_as(x)
Run Code Online (Sandbox Code Playgroud)
据我所知,文档:我相信这也可以作为一个自定义实现Function.子类Function需要一个backward()方法,但
Module不需要.同样,在线性的doc示例中Module,它取决于线性Function:
class Linear(nn.Module):
def __init__(self, input_features, output_features, bias=True):
...
def forward(self, input):
return Linear()(input, self.weight, self.bias)
Run Code Online (Sandbox Code Playgroud)
问题:我不明白之间的关系Module和Function.在上面的第一个清单(模块Testme)中,它是否应该有相关的功能?如果没有,那么就可以实现这个没有一个backward通过继承模块的方法,那么为什么一个Function总是需要一个backward方法是什么?
也许Functions仅适用于不是由现有火炬功能组成的功能?换句话说:Function如果他们的forward方法完全由先前定义的火炬函数组成,那么模块可能不需要关联?
我是 PyTorch 的新手,在使用不同的工具包一段时间后尝试了一下。
我想了解如何编写自定义图层和函数。作为一个简单的测试,我写了这个:
class Testme(nn.Module): ## it _is_ a sublcass of module ##
def __init__(self):
super(Testme, self).__init__()
def forward(self, x):
return x / t_.max(x)
Run Code Online (Sandbox Code Playgroud)
这旨在使通过它的数据总和为 1。实际上没有用,只是在测试中。
然后我将其插入 PyTorch Playground 中的示例代码:
def make_layers(cfg, batch_norm=False):
layers = []
in_channels = 3
for i, v in enumerate(cfg):
if v == 'M':
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
else:
padding = v[1] if isinstance(v, tuple) else 1
out_channels = v[0] if isinstance(v, tuple) else v
conv2d = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=padding)
if batch_norm:
layers += …Run Code Online (Sandbox Code Playgroud)