Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why not called function (forward) is called in pytorch class?

I have the following simple example code for linear regression as follows.import torch

import numpy as np
from torch.autograd import Variable
class linearRegression(torch.nn.Module):
    def __init__(self, inputSize, outputSize):
        super(linearRegression, self).__init__()
        self.linear = torch.nn.Linear(inputSize, outputSize)

    def forward(self, x):
        out = self.linear(x)
        return out

x = np.array([1], dtype = np.float32).reshape(-1, 1)
x = Variable(torch.from_numpy(x))

model = linearRegression(1, 1)
model(x)

the output is tensor([[0.4512]], grad_fn=<AddmmBackward>).

My question is how the output is made by not model.foward(x) but model(x).
In this code I have never called forward, but it seems to be called.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It is because the dunder method __call__ of nn.Module will internally call its user-defined forward method.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading