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

Patrice: <p>please, could anyone help me check where I did wrong?</p>
<p>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”.</p>
<p>please any help or suggestions would be highly appreciated</p>
<pre><code class="lang-auto">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) 
</code></pre>
<p>The training part is as follows:</p>
<pre><code class="lang-auto">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 &gt; 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)
</code></pre>

albanD: <p>Hi,</p>
<p>The issue is that you give an int instead of a Tensor as input to a convolution.<br>
I guess the problem is with your test code that does this?</p>
<pre><code class="lang-auto">num_classes = 2 
model = fcn(num_classes) 
</code></pre>

Patrice: <p>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.</p>

albanD: <p>Hi,</p>
<p>Can you give the full error message of where it happens?</p>
<p>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.</p>

Patrice: <pre><code class="lang-auto"> 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)
</code></pre>
<p>the error happens where i call the model (out=model(x)) in the testing section</p>
<p>the full error message is as follows:<br>
TypeError: conv2d(): argument ‘input’ (position 1) must be Tensor, not int</p>

albanD: <p>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 <code>forward</code> somewhere and will help you narrow down the problem.</p>

Patrice: <p>Generally, when an error happens, it shows you the line number in the codes, right?<br>
This is the whole error message</p>
<pre><code class="lang-auto">File "e:\Torch works\project\transfer32.py", line 282, in &lt;module&gt;

    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
</code></pre>

Patrice: <p>And line 282 corresponds to the out=model(x) in the testing section of my codes</p>

albanD: <p>The error is in</p>
<pre><code class="lang-auto">  File "e:\Torch works\project\transfer32.py", line 205, in forward

    x = self.stage1(x)
</code></pre>
<p>You can try and add a print in your forward function to check what is <code>x</code> here?</p>

Patrice: <aside class="quote no-group quote-modified" data-username="Patrice" data-post="7" data-topic="71821">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/p/e274bd/48.png" class="avatar"> Patrice:</div>
<blockquote>
<p>File “C:\ProgramData\Anaconda3\lib\site-packages\torch\nn\modules\conv.py”, line 345, in forward return self.conv2d_forward(input, self.weight)</p>
</blockquote>
</aside>
<p>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</p>

albanD: <p>The problem is that <code>x</code> seems to be an <code>int</code> while it should be a <code>Tensor</code>.</p>

Patrice: <p>I have tried to convert my inputs to a pytorch tensor as follows</p>
<pre><code class="lang-auto">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)
</code></pre>
<p>I have now gotten another error. Please, any idea on how to solve it?<br>
RuntimeError: Expected 4-dimensional input for 4-dimensional weight 64 9 7 7, but got 0-dimensional input of size [] instead</p>

albanD: <p>Can you just print what <code>data</code> contains here? Just to make sure? What is the type of its elements?</p>

Patrice: <p>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</p>
<pre><code class="lang-auto"> 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)
       
</code></pre>
<p>Before, I had written the first line as</p>
<pre><code class="lang-auto"> for  data in enumerate(test_loader):  
</code></pre>
<p>and this way is wrong</p>