'TypeError: forward() takes 1 positional argument but 2 were given
class DeConv2d(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, stride, padding, dilation):
super().__init__()
self.up = nn.Upsample(scale_factor=2, mode='nearest')
self.conv = nn.Conv2d(in_channel, out_channel, kernel_size=kernel_size, \
stride=stride, padding=padding, dilation=dilation)
def forward(self, x):
output = self.up(x)
output = self.conv(output)
return output
class EncoderDecoder(nn.Module):
def __init__(self, pretrained_net, n_class):
super().__init__()
self.n_class = n_class
self.pretrained_net = pretrained_net
self.relu = nn.ReLU(inplace=True)
self.deconv1 = DeConv2d(512, 512, kernel_size=3, stride=1, padding=1, dilation=1)
self.bn1 = nn.BatchNorm2d(512)
self.deconv2 = DeConv2d(512, 256, kernel_size=3, stride=1, padding=1, dilation=1)
self.bn2 = nn.BatchNorm2d(256)
self.deconv3 = DeConv2d(256, 128, kernel_size=3, stride=1, padding=1, dilation=1)
self.bn3 = nn.BatchNorm2d(128)
self.deconv4 = DeConv2d(128, 64, kernel_size=3, stride=1, padding=1, dilation=1)
self.bn4 = nn.BatchNorm2d(64)
self.classifier = nn.Conv2d(64, n_class, kernel_size=1)
def forward(self, x):
output=self.pretrained_net.layers(x)
output=self.relu(self.deconv1(output))
output=self.bn1(output)
output=self.relu(self.deconv2(output))
output=self.bn2(output)
output=self.relu(self.deconv3(output))
output=self.bn3(output)
output=self.relu(self.deconv4(output))
output=self.bn4(output)
output=self.classifier(output)
return output
this is my code and I don't know why the type error exist . Does somebody know how to fix these problems?
Solution 1:[1]
When you create a class, and define a function with self
args within the class, self is autofilled with the class.Ex:
class item():# create a random class
self.var = 0
def fun(self,x):
self.var +=x
n = item()
And you can try add:
n.fun(3)
print(n.var)
returns 3
self
argument is autofilled with class itself
Solution 2:[2]
In my case, I used transformers.Trainer.train()
to train my model
. And then I used predict_scores = model(predict_dataset)
to get the prediction result. But I got the same error as "forward() takes 1 positional argument but 2 were given...".
Then I changed to predict_scores = trainer.predict(predict_dataset)
, then I got the correct result. Hope this is helpful to others. I am a newbie to PyTorch.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | okie |
Solution 2 | taichi_tiger |