Hello, I am trying to do linear regression with object oriented technique in Pytorch. I have implemented the following code. And I am getting an error that the model defined by me has no attribute ‘_module’ when I try to run self.model.train() in the trainer class that I created.
Here is the code for the regression class and the error associated with it.
class LinearRegressioScratch(nn.Module):
# STEP 0: Define all the required parameters
def __init__(self, lr, num_inputs, optimizer, sigma=0.01):
self.sigma =sigma
self.lr = lr
self.num_inputs = num_inputs
self.optimizer = optimizer
self.w = torch.normal(0, sigma, (num_inputs, 1), requires_grad=True) # Setting parameter W as a tensor with rows equal to num_inputs and columns 1
self.b = torch.zeros(1, requires_grad=True) # Set the other parameter b equal to 1
# STEP 1: Forward pass through the network. In this case, just a linear equation for the moldel
def forward(self, X):
return torch.matmul(X, self.w) + self.b
# STEP 2: Calculating the loss for the predicted and the actual value.
def loss(self, y_hat, y):
squared_difference = torch.sum((y_hat-y)**2)
loss = squared_difference/len(y)
return loss
# STEP 3: Backpropagation and adjusting the parameters of the network. The last step of updating the parameter is combined into this step.
def configure_optimizer(self):
"""
This method will return an instance of the class SGD.
It will return whatever the optimizer we have used to update the parameters based on the loss calculated in the steps above.
For different list of optimizers check the module optimizer.py
"""
return self.optimizer([self.w, self.b], self.lr)
Error that I get
Traceback (most recent call last):
File "d:\TU Kaiserslautern CVT\Coursework\Pytorch\Linear_regression_implementation_from_scratch\Linear_Regression_Implementation.py", line 16, in <module>
trainer.fit(model, data)
File "d:\TU Kaiserslautern CVT\Coursework\Pytorch\Linear_regression_implementation_from_scratch\Trainer_regular.py", line 32, in fit
self.fit_epoch()
File "d:\TU Kaiserslautern CVT\Coursework\Pytorch\Linear_regression_implementation_from_scratch\Trainer_regular.py", line 40, in fit_epoch
self.model.train()
File "C:\Users\DELL\anaconda3\envs\torch_env\lib\site-packages\torch\nn\modules\module.py", line 1910, in train
for module in self.children():
File "C:\Users\DELL\anaconda3\envs\torch_env\lib\site-packages\torch\nn\modules\module.py", line 1796, in children
for name, module in self.named_children():
File "C:\Users\DELL\anaconda3\envs\torch_env\lib\site-packages\torch\nn\modules\module.py", line 1815, in named_children
for name, module in self._modules.items():
File "C:\Users\DELL\anaconda3\envs\torch_env\lib\site-packages\torch\nn\modules\module.py", line 1270, in __getattr__
type(self).__name__, name))
AttributeError: 'LinearRegressioScratch' object has no attribute '_modules'