Issue
I am passing a batch of 256 images x_s with the following dimensions [256, 3, 560, 448]. However I whenever i try to feed my images to the CNN i get the following error:
ErrorTypeError: __init__() takes 1 positional argument but 2 were given'
Not sure what it means here by '1 positional argument'. I am passing in the images using an iterator which I created. Below is my code for the training loop up until the point where it breaks:
for e in range(num_epochs):
print(f'Epoch{e+1:04d}/ {num_epochs:04d}', end='\n================\n')
dl_source_iter = iter(dl_source)
dl_target_iter = iter(dl_target)
for batch in range(max_batches):
optimizer.zero_grad()
p = float(batch + e * max_batches) / (num_epochs *max_batches)
grl_lambda = 2. / (1. + np.exp(-10 * p)) - 1
x_s, y_s = next(dl_source_iter)
y_s_domain = torch.zeros(256, dtype=torch.long)
class_pred, domain_pred = Cnn(x_s, grl_lambda) #This is the line which throws an error
Here is my convolutional neural network:
class Cnn(nn.Module):
def __init__(self):
super(Cnn, self).__init__()
self.feature_extract= nn.Sequential(
nn.Conv2d(3, 64, 5, 1, 1),
nn.BatchNorm2d(64),
nn.MaxPool2d(2),
nn.ReLU(True),
nn.Conv2d(64, 50, 5, 1, 1),
nn.BatchNorm2d(50),
nn.MaxPool2d(2),
nn.ReLU(True),
nn.Dropout2d(),
)
self.num_cnn_features = 50*5*5
self.class_classifier = nn.Sequential(
nn.Linear(self.num_cnn_features, 200),
nn.BatchNorm1d(200),
nn.Dropout2d(),
nn.ReLU(True),
nn.Linear(200, 200),
nn.BatchNorm1d(200),
nn.ReLU(True),
nn.Linear(200, 182),
nn.LogSoftmax(dim = 1),
)
self.DomainClassifier = nn.Sequential(
nn.Linear(self.num_cnn_features, 100),
nn.BatchNorm1d(100),
nn.ReLU(True),
nn.Linear(100, 2),
nn.LogSoftmax(dim=1)
)
def forward(self, x, grl_lambda=1.0):
features = self.feature_extract(x)
features = features.view(-1, self.num_cnn_features)
features_grl = GradientReversalFn(features, grl_lambda)
class_pred = self.class_classifier(features)
domain_pred = self.DomainClassifier(features_grl)
return class_pred, domain_pred
Does anyone have any guesses as to why this might be happening? I can't seem to figure out what is going wrong. Any help would be greatly appreciated.
Solution
You need to create a Cnn
object before you can pass data to it. You are calling the Cnn
class constructor __init__
, which expects no arguments, rather than the forward
method for an instance of the Cnn
class, which is what you actually want to do.
# outside of loop
model = Cnn()
# inside loop
class_pred, domain_pred = model(x_s, grl_lambda)
Answered By - DerekG
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.