gpt4 book ai didi

torch - pytorch自定义层 "is not a Module subclass"

转载 作者:行者123 更新时间:2023-12-01 23:21:26 33 4
gpt4 key购买 nike

我是 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)

其目的是使通过它的数据总和为 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 += [conv2d, nn.BatchNorm2d(out_channels, affine=False), nn.ReLU()]
else:
layers += [conv2d, nn.ReLU()]
layers += [Testme] # here <------------------
in_channels = out_channels
return nn.Sequential(*layers)

结果是错误的!

TypeError: model.Testme is not a Module subclass

也许这需要是一个函数而不是一个模块?也不清楚 Function、Module 之间有什么区别。

例如,为什么函数需要 backward(),即使它完全由标准 pytorch 原语构建,而模块不需要这个?

最佳答案

这很简单。您几乎明白了,但是您忘记了实际创建新类 Testme 的实例。即使特定类的实例的创建不带任何参数(对于 Testme),您也需要这样做。但它比卷积层更容易忘记,通常会向卷积层传递很多参数。

将您指示的行更改为以下内容,您的问题就得到解决。

layers += [Testme()]

关于torch - pytorch自定义层 "is not a Module subclass",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44406819/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com