Conv2d(): argument 'input' (position 1) must be Tensor, not int

please, could anyone help me check where I did wrong?

I am trying to build up a FCN model for binary segmentation. I have managed to design the following network which can train. However, when it gets to the validation loop, it gives the following error “cnv2d(): argument ‘input’ (position 1) must be Tensor, not int”.

please any help or suggestions would be highly appreciated

class fcn(nn.Module):

    def __init__(self, num_classes):

        super(fcn, self).__init__()

        self.stage1 = nn.Sequential(*list(pretrained_net.children())[:-4])

        # change input channels to 9

        self.stage1[0] = nn.Conv2d(9, 64, kernel_size=7, stride=2, padding=3, bias=False)

        self.stage2 = list(pretrained_net.children())[-4]

        self.stage3 = list(pretrained_net.children())[-3]

        self.scores1 = nn.Conv2d(512, num_classes, 1)

        self.scores2 = nn.Conv2d(256, num_classes, 1)

        self.scores3 = nn.Conv2d(128, num_classes, 1)

        self.upsample_8x = nn.ConvTranspose2d(num_classes, num_classes, 16, 8, 4, bias=False)

        self.upsample_4x = nn.ConvTranspose2d(num_classes, num_classes, 4, 2, 1, bias=False)

        self.upsample_2x = nn.ConvTranspose2d(num_classes, num_classes, 4, 2, 1, bias=False)

    def forward(self, x):

        x = self.stage1(x)

        s1 = x  # 1/8

        x = self.stage2(x)

        s2 = x  # 1/16

        x = self.stage3(x)

        s3 = x  # 1/32

        s3 = self.scores1(s3)

        s3 = self.upsample_2x(s3)

        s2 = self.scores2(s2)

        s2 = s2 + s3

        s1 = self.scores3(s1)

        s2 = self.upsample_4x(s2)

        s = s1 + s2

        s = self.upsample_8x(s2)

        return s

num_classes = 2 

pretrained_net = models.resnet18(pretrained=True)

model = fcn(num_classes) 

The training part is as follows:

weights = torch.tensor([0.75, 1], dtype=torch.float)

criterion = nn.CrossEntropyLoss(weight=weights)

basic_optim = torch.optim.SGD(model.parameters(), lr=0.05, weight_decay=0.00001)

optimizer = basic_optim 

Epoch_num=5

for e in range(Epoch_num):

    print('Epoch', e+1)

    train_loss = 0

    model= model.train()

    

    for idx, data in enumerate(train_loader):

        x, y_true = data

        if torch.cuda.is_available():

            x, y_true = x.cuda(), y_true.cuda()

        # forward

        out = model(x)

        out = F.softmax(out, dim=1)

        #out = out > 0.5

        loss = criterion(out, y_true)

        optimizer.zero_grad()

        loss.backward()

        optimizer.step()

        train_loss += loss.item()

        if idx % 100 == 0 and idx != 0:

            print('[{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(

                 idx , len(train_loader.dataset),

                100. * idx / len(train_loader), train_loss/ idx))

    model= model.train(False)

    

    for  data in enumerate(test_loader):

       

        x, y_true = data 

        if torch.cuda.is_available():

            x, y_true = x.cuda(), y_true.cuda()

        out = model(x)

        out = F.softmax(out, dim=1)

        loss = criterion(out, y_true)

Hi,

The issue is that you give an int instead of a Tensor as input to a convolution.
I guess the problem is with your test code that does this?

num_classes = 2 
model = fcn(num_classes) 

Yes, it gives this error when it gets to the testing section. Please, how can I solve this? I am sorry, I am very new to Pytorch and a beginner in programming as well.

Hi,

Can you give the full error message of where it happens?

Also the convolution expects a Tensor as input, not just a python number. So you should make sure that you have a Tensor where the error happens.

 model= model.train(False)

    for  data in enumerate(test_loader):
       
        x, y_true = data 

        if torch.cuda.is_available():
            x, y_true = x.cuda(), y_true.cuda()

        out = model(x)
        out = F.softmax(out, dim=1)
        loss = criterion(out, y_true)

the error happens where i call the model (out=model(x)) in the testing section

the full error message is as follows:
TypeError: conv2d(): argument ‘input’ (position 1) must be Tensor, not int

The error should contain a stack trace of where it happened. Like where you where in the code when the error happened. This will point in the forward somewhere and will help you narrow down the problem.

Generally, when an error happens, it shows you the line number in the codes, right?
This is the whole error message

File "e:\Torch works\project\transfer32.py", line 282, in <module>

    out = model(x)

  File "C:\ProgramData\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 541, in __call__

    result = self.forward(*input, **kwargs)

  File "e:\Torch works\project\transfer32.py", line 205, in forward

    x = self.stage1(x)

  File "C:\ProgramData\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 541, in __call__

    result = self.forward(*input, **kwargs)

  File "C:\ProgramData\Anaconda3\lib\site-packages\torch\nn\modules\container.py", line 92, in forward

    input = module(input)

  File "C:\ProgramData\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 541, in __call__

    result = self.forward(*input, **kwargs)

  File "C:\ProgramData\Anaconda3\lib\site-packages\torch\nn\modules\conv.py", line 345, in forward

    return self.conv2d_forward(input, self.weight)

  File "C:\ProgramData\Anaconda3\lib\site-packages\torch\nn\modules\conv.py", line 342, in conv2d_forward

    self.padding, self.dilation, self.groups)

TypeError: conv2d(): argument 'input' (position 1) must be Tensor, not int

And line 282 corresponds to the out=model(x) in the testing section of my codes

The error is in

  File "e:\Torch works\project\transfer32.py", line 205, in forward

    x = self.stage1(x)

You can try and add a print in your forward function to check what is x here?

Please, I would like to know what might be the problem? The training section of my codes is written in exactly the same way and it can run. But, it does not run when it gets to the testing section

The problem is that x seems to be an int while it should be a Tensor.

I have tried to convert my inputs to a pytorch tensor as follows

model= model.train(False)

    for  data in enumerate(test_loader):
       
        x, y_true = data 

        if torch.cuda.is_available():
            x, y_true = x.cuda(), y_true.cuda()
        x=torch.from_numpy(np.asarray(x))
        out = model(x)
        out = F.softmax(out, dim=1)
        loss = criterion(out, y_true)

I have now gotten another error. Please, any idea on how to solve it?
RuntimeError: Expected 4-dimensional input for 4-dimensional weight 64 9 7 7, but got 0-dimensional input of size [] instead

Can you just print what data contains here? Just to make sure? What is the type of its elements?

Dear Alban, thanks very much for your time and guidance. I have been able to figure it out. It was just a syntax problem. I changed the first line as shown below and it works

 for i, data in enumerate(test_loader): 
    
        x, y_true = data 

        if torch.cuda.is_available():
         x, y_true = x.cuda(), y_true.cuda()
        out = model(x)
        out = F.softmax(out, dim=1)
        loss = criterion(out, y_true)
       

Before, I had written the first line as

 for  data in enumerate(test_loader):  

and this way is wrong

1 Like