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

标签 torch pytorch autograd

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

相关文章:

lua - 如何清除itorch笔记本中单元格中的输出?

shell - torch 安装没有 curl

python - 将 PyTorch 代码从 CPU 移植到 GPU

python - PyTorch autograd——只能为标量输出隐式创建 grad

c++ - 如何从libtorch输出中删除乘法器并显示最终结果?

python - 类型错误 : cannot unpack non-iterable int object

python - 如何在同一个 docker 镜像上使用不同类型的 gpus(例如 1080Ti 与 2080Ti)而无需重新运行 `python setup.py develop`?

python - PyTorch 张量中的就地算术运算与普通算术运算

mathematical-optimization - 如何在pytorch中手动应用渐变

python - 为什么使用 loss.backward() 与 torch.auto.grad 时梯度不相等?