[PYTHON] When you get a cannot assign module before Module.init () call in pytorch

It's a very simple story, but it's a memorandum because it seems to melt for a long time someday.

Corresponding code and error content

import torch
import torch.nn as nn

class Encoder(nn.Module):
    def __init__(self, p_n_features_num, timesteps) -> None:
        self.p_n_features_num = p_n_features_num
        self.linear = nn.Linear(
            p_n_features_num, p_n_features_num, bias=True)
        self.leakyrelu = nn.LeakyReLU()

    def forward(self, input_net):
        input_net = input_net.view(input_net.size(0), self.p_n_features_num)
        return self.leakyrelu(self.linear(input_net))

If you call \ _ \ _ init \ _ \ _ of Encoder here

cannot assign module before Module.init() call


```I get the error.

## Solution, fix code
 This is because the super method was not called first because it inherited nn.Module at the time of init. Therefore, it can be fixed by modifying it as follows.

```python
import torch
import torch.nn as nn

class Encoder(nn.Module):
    def __init__(self, p_n_features_num, timesteps) -> None:
        super(Encoder, self).__init__()
        self.p_n_features_num = p_n_features_num
        self.linear = nn.Linear(
            p_n_features_num, p_n_features_num, bias=True)
        self.leakyrelu = nn.LeakyReLU()

    def forward(self, input_net):
        input_net = input_net.view(input_net.size(0), self.p_n_features_num)
        return self.leakyrelu(self.linear(input_net))

Recommended Posts

When you get a cannot assign module before Module.init () call in pytorch
When you can't call base.html in Django
When I get a chromedriver error in Selenium
[Python] What to check when you get a Unicode Decode Error in Django
I get a java.util.regex.PatternSyntaxException when splitting a string in PySpark
BigQuery-If you get a Reason: responseTooLarge error in Python
When you want to plt.save in a for statement
When you get an error in python scraping (requests)
[Small story] A painstaking measure when you have to execute a function before import in Python
What to do if you get a Cannot retrieve metalink for repository error in yum
What to do if you get a must override `get_config` error when trying to model.save in Keras
If you get stuck in Cannot load mkl_intel_thread.dll in Python on Windows
What to do if you get a minus zero in Python
If you want to assign csv export to a variable in python
I get a can't set attribute when using @property in python
[Python] What to do if you get a ModuleNotFoundError when importing pandas using Jupyter Notebook in Anaconda