Home > Software engineering >  I am new to pytorch , why am I getting the attribute error even after adding super(ClassName,self)._
I am new to pytorch , why am I getting the attribute error even after adding super(ClassName,self)._

Time:06-30

I am working on a chatbot based out of pytorch I am unable to figure out the reason behind the attribute error even after adding super to the NueralNet class. Using jupyter notebook for this project.

HERE IS MY CODE SO FAR , parts from both model.ipynb and train.ipynb


class NeuralNet(nn.Module):
    def __init__(self, input_size, hidden_size, num_classes):
        super().__init__()
        self.l1 = nn.Linear(input_size, hidden_size) 
        self.l2 = nn.Linear(hidden_size, hidden_size) 
        self.l3 = nn.Linear(hidden_size, num_classes)
        self.relu = nn.ReLU()
    
    
#Train

import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader

from ipynb.fs.full.model import NeuralNet

class ChatDataset(Dataset):

    def __init__(self):
        self.n_samples = len(x_train)
        self.x_data = x_train
        self.y_data = y_train
    
#hyperParameters
batch_size = 8
hidden_size = 8
output_size = len(tags)
input_size = len(all_words)
# print(input_size, len(all_words))
# print(output_size, tags)
learning_rate = 0.001
num_epochs = 1000
    
dataset = ChatDataset()
train_loader = DataLoader(dataset = dataset , batch_size=batch_size, shuffle=True, num_workers=2)  
model = NeuralNet(input_size, hidden_size, output_size)```




 

ERROR:


~\Untitled Folder\model.ipynb in __init__(self, input_size, hidden_size, num_classes)
      9    "source": [
     10     "import torch\n",
---> 11     "import torch.nn as nn"
     12    ]
     13   },

~\anaconda3a\lib\site-packages\torch\nn\modules\module.py in __setattr__(self, name, value)
   1234             if isinstance(value, Module):
   1235                 if modules is None:
-> 1236                     raise AttributeError(
   1237                         "cannot assign module before Module.__init__() call")
   1238                 remove_from(self.__dict__, self._parameters, self._buffers, self._non_persistent_buffers_set)

AttributeError: cannot assign module before Module.__init__() call

CodePudding user response:

This is most probably because you haven't called super().__init__ in your __init__ function of NeuralNet before registering sub-modules to it. See here for additional details.

The only missing component is a function __len__ on ChatDataset. Other than that the provided code runs fine.

  • Related