pytorch custom layer "is not a Module subclass"

forgotmysocks

I am new to PyTorch, trying it out after using a different toolkit for a while.

I would like understand how to program custom layers and functions. And as a simple test, I wrote this:

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)

which is intended to cause the data passing through it to sum to 1. Not actually useful, just at test.

Then I plug it to the example code from the 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)

The result is an error!

TypeError: model.Testme is not a Module subclass

Maybe this needs to be a Function rather than a Module? Also not clear what the difference is between Function, Module.

For example, why does a Function need a backward(), even if it is constructed entirely from standard pytorch primitive, whereas a Module does not need this?

mbpaulus

That's a simple one. You almost got it, but you forgot to actually create an instance of your new class Testme. You need to do this, even if the creation of an instance of a particular class doesn't take any parameters (as for Testme). But it's easier to forget than for a convolutional layer, to which you typically pass a lot of arguments.

Change the line you have indicated to the following and your problem is resolved.

layers += [Testme()]

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Different methods for initializing embedding layer weights in Pytorch

分類Dev

Will custom Lambda layer be included in the backpropagating in Keras

分類Dev

keras bidirectional layer with custom RNN Cell

分類Dev

Upgrading (overriding) an entire recipe in a custom layer

分類Dev

Custom convolution kernel and toroidal convolution in PyTorch

分類Dev

Output layer doesn't have activation function in custom estimator

分類Dev

How to support masking in custom tf.keras.layers.Layer

分類Dev

mapbox gl js: use intermediate rendering step as mask for custom layer

分類Dev

How to implement custom output layer with dynamic shape in Keras?

分類Dev

Pytorch Linear Layerは、入力の形状を自動的に変更しますか?

分類Dev

How do I make custom pytorch datasets structured like the torchvision datasets?

分類Dev

AVPlayerLayer Position in UIView Layer

分類Dev

IoC in Domain Layer

分類Dev

Modify layer parameters in Keras

分類Dev

Splitting cnn layer in keras

分類Dev

Crop a video layer in an AVComposition

分類Dev

Controlling access to a communication layer

分類Dev

CSS multiple layer border?

分類Dev

Autowiring sessionFactory in service layer

分類Dev

Data Layer Properties in GTM

分類Dev

Structuring a Data Access Layer

分類Dev

PytorchのLSTM

分類Dev

PyTorch-contiguous()

分類Dev

reshaping a tensor with padding in pytorch

分類Dev

PyTorch Softmax Dimensions error

分類Dev

How to invert a PyTorch Embedding?

分類Dev

Plot the derivative of a function with PyTorch?

分類Dev

詩とPyTorch

分類Dev

calculate perplexity in pytorch