RuntimeError: Given groups=1, weight of size [32, 3, 4, 4], expected input[64, 1, 340, 340] to have 3 channels, but got 1 channels instead

Hbert16: <p>I have this problem and cannot solve it.</p>
<p>This is my Dataset:</p>
<pre><code class="lang-auto">class Data(Dataset):
    def __init__(self, df, data_dir, transform):
        super().__init__()
        self.df = df
        self.data_dir = data_dir
        self.transform = transform

    def __len__(self):
        return len(self.df)

    def __getitem__(self, index):
        img_name = self.df.id[index]
        label = self.df.broken[index]

        img_path = os.path.join(str(self.data_dir), str(img_name) + '.png')
        img = mpimg.imread(img_path)
        img = self.transform(img)
        return img, label
</code></pre>
<p>This is my model:</p>
<pre><code class="lang-auto">class SkullCNN(nn.Module):
    def __init__(self):
        super(SkullCNN, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2d(3, 32, 4, 2, 0),
            nn.BatchNorm2d(32),
            nn.ReLU()
        )
        # 1 + (32 - 4 + 0)/2 = 15
        # 32 * 15 * 15
        self.conv2 = nn.Sequential(
            nn.Conv2d(32, 64, 3, 2, 0),
            nn.BatchNorm2d(64),
            nn.ReLU()
        )
        # 1 + (15 - 3 + 0)/2 = 7
        # 64 * 7 * 7
        self.conv3 = nn.Sequential(
            nn.Conv2d(64, 128, 3, 2, 0),
            nn.BatchNorm2d(128),
            nn.ReLU()
        )
        # 1 + (7 - 3 + 0)/2 = 3
        # 128 * 3 * 3
        self.conv4 = nn.Sequential(
            nn.Conv2d(128, 256, 3, 2, 0),
            nn.BatchNorm2d(256),
            nn.ReLU()
        )
        #  1 + (3 - 3 + 0)/2 = 1
        # 256 * 1 * 1
        
        self.fc = nn.Sequential(
            nn.Linear(256*1*1, 1024),
            nn.ReLU(),
            nn.Dropout(p=0.2),
            nn.Linear(1024,2)
        )
    def forward(self, x):
        x = self.conv1(x)

        x = self.conv2(x)

        x = self.conv3(x)

        x = self.conv4(x)

        x = x.view(x.shape[0],-1)
        x = self.fc(x)
        return x
</code></pre>
<p>This is the code block where the error is generated:</p>
<pre><code class="lang-auto">num_epochs = 25
num_classes = 2
batch_size = 128

for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        images = images.to(device)
        labels = labels.to(device)
#         print(images[0].shape)
        
        out = model(images)
        loss = criterion(out, labels)
        
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    print('Epoch: {}/{}, Loss: {}'.format(epoch+1, num_epochs, loss.item()))
</code></pre>
<p>The error output is:</p>
<pre><code class="lang-auto">---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
&lt;ipython-input-72-15d7d37170f1&gt; in &lt;module&gt;()
      9 #         print(images[0].shape)
     10 
---&gt; 11         out = model(images)
     12         loss = criterion(out, labels)
     13 

6 frames
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/conv.py in _conv_forward(self, input, weight)
    348                             _pair(0), self.dilation, self.groups)
    349         return F.conv2d(input, weight, self.bias, self.stride,
--&gt; 350                         self.padding, self.dilation, self.groups)
    351 
    352     def forward(self, input):

RuntimeError: Given groups=1, weight of size [32, 3, 4, 4], expected input[64, 1, 340, 340] to have 3 channels, but got 1 channels instead
</code></pre>
<p>Please help me, I’m learning PyTorch. Thank you so much, also I see some similar problems here, but I can’t adapt it to my code.</p>

Nikronic: <p>Hi,<br>
Actually, the error is happening in this line.</p>
<aside class="quote no-group quote-modified" data-username="Hbert16" data-post="1" data-topic="89626">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/hbert16/48/26838_2.png" class="avatar"> Hbert16:</div>
<blockquote>
<p><code>            nn.Conv2d(3, 32, 4, 2, 0),</code><br>
…<br>
x = self.conv1(x)</p>
</blockquote>
</aside>
<p>The issue is that when you are loading your images using <code>for</code> loop on <code>train_loader</code> it returns tensors of size <code>[batch_size, 1, height, width]</code> and your first convolution layer is <code>nn.Conv2d(3, 32, ...)</code> which expects <code>3</code> channels not <code>1</code>.<br>
Probably your images are grayscale so they have 1 channel. Changing <code>conv1</code> of model to below can solve:</p>
<pre><code class="lang-auto">nn.Conv2d(1, 32, 4, 2, 0),
</code></pre>
<p>Bests</p>

Hbert16: <p>I changed, but i get the same error:(.</p>
<p>I change my code like this:</p>
<pre><code class="lang-auto">class SkullCNN(nn.Module):
    def __init__(self):
        super(SkullCNN, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2d(1, 32, 4, 2, 0),
            nn.BatchNorm2d(32),
            nn.ReLU()
        )
        #...

</code></pre>
<p>The images I trying process look like this:<br>
<img src="https://discuss.pytorch.org/uploads/default/original/3X/a/7/a77e3903a175e98b95b92371ef09f76959e919b3.png" alt="0" data-base62-sha1="nTIarCTYvKWB8mJV7PKLRq8zyOD" width="340" height="340"></p>
<p>And i get the same error:</p>
<pre><code class="lang-auto">---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
&lt;ipython-input-174-15d7d37170f1&gt; in &lt;module&gt;()
      9 #         print(images[0].shape)
     10 
---&gt; 11         out = model(images)
     12         loss = criterion(out, labels)
     13 

6 frames
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/conv.py in _conv_forward(self, input, weight)
    348                             _pair(0), self.dilation, self.groups)
    349         return F.conv2d(input, weight, self.bias, self.stride,
--&gt; 350                         self.padding, self.dilation, self.groups)
    351 
    352     def forward(self, input):

RuntimeError: Given groups=1, weight of size [32, 3, 4, 4], expected input[64, 1, 32, 32] to have 3 channels, but got 1 channels instead
</code></pre>

Nikronic: <p>It’s strange! Can you share full stack trace error that shows which line is giving the error?</p>
<p>I ran your code for making sure about it and the proposed change should absolutely work. I guess your IDE/Kernel did not use changed file as you are having the exact same error which only can happen in that particular line given the weights and shapes.</p>