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

username: jyothi_sri
cooked: <p>class Network(nn.Module):<br>
def <strong>init</strong>(self,kernels1=1,extra_kernels=0):<br>
super().<strong>init</strong>()<br>
self.conv1 =  nn.Conv2d(in_channels = 3, out_channels = 64, kernel_size = 5, padding = (1,1))#,kernels=kernels1, stride=1)<br>
self.bn1 = nn.BatchNorm2d(64,eps=1e-05,momentum=0.15)<br>
self.cnn1_drop = nn.Dropout2d(p=0.15)<br>
self.conv2 = nn.Conv2d (in_channels = 64, out_channels = 128, kernel_size = 4, padding = (1,1))<br>
self.cnn2_drop = nn.Dropout2d(p=0.15)<br>
self.bn2 = nn.BatchNorm2d(128,eps=1e-05,momentum=0.25)<br>
self.conv3 = nn.Conv2d(in_channels = 128, out_channels = 256, kernel_size = 3, padding = (1,1))<br>
self.bn3 = nn.BatchNorm2d(256,eps=1e-05,momentum=0.25)<br>
self.cnn3_drop = nn.Dropout2d(p=0.25)<br>
self.relu=nn.ELU(alpha=6.0)<br>
self.fc1 = nn.Linear(in_features =57600,out_features= 1000)<br>
self.bn4 = nn.BatchNorm1d(1000)<br>
self.cnn4_drop = nn.Dropout2d(p=0.25)<br>
self.fc2 = nn.Linear(in_features = 1000, out_features = 100)<br>
self.bn5 = nn.BatchNorm1d(100)<br>
self.cnn5_drop = nn.Dropout2d(p=0.25)<br>
self.out = nn.Linear(in_features = 100, out_features = 1)<br>
<span class="hashtag">#self</span>.cnn6_drop = nn.Dropout2d(p=0.25)</p>
<pre><code>def forward(self, t):
    t = t.view(-1, t.size(-3), t.size(-2), t.size(-1))
    #print('t', str(t.size()))
    t = self.relu(self.bn1(self.conv1(t)))
    #t=lip2d(t,kernel=3, stride=2, padding=1)
    t = F.max_pool2d(t, kernel_size = 2, stride = 2)
    t = self.cnn1_drop(t)
    #t = self.conv1(t)
   # t = F.max_pool2d(t,(t.size(-2), t.size(-1)))
   # t1 = -F.max_pool2d(-t,(t.size(-2), t.size(-1)))
    #t  = torch.cat((t, t1),1)
    #t = t.squeeze(3).squeeze(2)
    #t = t.view (t.size(0),-1)
    #t  = t.unsqueeze(3).unsqueeze(2)
    t = self.relu(self.bn2(self.conv2(t)))
    t = F.max_pool2d(t, kernel_size = 2, stride = 2)
    t =self.cnn2_drop(t)
    t = self.relu(self.bn3(self.conv3(t)))
    t = F.max_pool2d(t, kernel_size = 2, stride = 2)
    t =self.cnn3_drop(t)
    t = t.view (t.size(0),-1)
    t = self.relu(self.bn4(self.fc1(t)))
    t =self.cnn4_drop(t)
    t = self.relu(self.bn5(self.fc2(t)))
    t =self.cnn5_drop(t)
    t = self.out(t)
    #t =self.cnn6_drop(t)
    
    return t
</code></pre>
<p>I am trying dis code , when i run it got the following error<br>
RuntimeError: Given groups=1, weight of size [64, 3, 5, 5], expected input[64, 1, 128, 128] to have 3 channels, but got 1 channels instead</p>

username: ptrblck
cooked: <p>Based on the error message it seems you are passing an input with a single channel while 3 are expected. You could change the <code>in_channels</code> argument of the first conv layer to <code>1</code> or make sure the input has 3 channels.</p>

username: jyothi_sri
cooked: <p>def default_loader(path):<br>
return Image.open(path).convert(‘RGB’) this is how i m passing input, from this function it means i m passing RGB images only right .how to make sure whether i m passing RGB images only</p>

username: jyothi_sri
cooked: <p>is it correct what i did?<br>
<strong>def default_loader(path):</strong><br>
**      return Image.open(path).convert(‘RGB’)**</p>

username: ptrblck
cooked: <p>Yes, this looks correct.<br>
Check the shape of <code>t</code> inside the <code>forward</code> and see if it still reports a single channel.<br>
Also, I don’t understand why you are using a <code>view</code> operation here, which should not change anything assuming the input is already a 4D tensor:</p>
<pre><code class="lang-python">t = t.view(-1, t.size(-3), t.size(-2), t.size(-1))
</code></pre>

username: jyothi_sri
cooked: <p>ok will check .i can remove this t = t.view(-1, t.size(-3), t.size(-2), t.size(-1)) and dirctly feed input to conv1 layer</p>

username: jyothi_sri
cooked: <p>t torch.Size([64, 1, 128, 128]) this is taking single channel as input .how to pass 3channels</p>

username: ptrblck
cooked: <p>Try to narrow down why the input has a single channel as you expect it to have 3 based on your current description. I.e. check the output of the <code>DataLoader</code>, then the output of the <code>Dataset</code>, then the <code>__getitem__</code> and narrow down why the <code>convert("RGB")</code> call is used.</p>

username: jyothi_sri
cooked: <p>i didnt get u properly, can u be more clear as i m beginner to this pytorch an when i give the input directly to conv1 layer without <em>view</em>  operation i got this error<br>
ValueError: too many values to unpack (expected 4)</p>

username: jyothi_sri
cooked: <p>Sir ,please tell me how to pass on 3channels</p>

username: srishti-git1110
cooked: <p><a class="mention" href="/u/jyothi_sri">@jyothi_sri</a><br>
As <a class="mention" href="/u/ptrblck">@ptrblck</a> has mentioned, you should narrow down your debugging to the outputs of your custom Dataset class and Dataloader first, as the problem essentially lies with the dimensionality of your input tensors and those are the two classes that (should) primarily deal with putting the data in a format compatible with the model.</p>
<p>Otherwise, you could post the code of those two classes here for us to look at and potentially help you.<br>
Please also ensure to enclose your code within a block that begins and ends with ```</p>

username: jyothi_sri
cooked: <p>‘’'class IQADataset(Dataset):<br>
def <strong>init</strong>(self, conf, exp_id=0, status=‘train’, loader=default_loader):<br>
self.loader = loader<br>
im_dir = conf[‘im_dir’]<br>
self.patch_size = conf[‘patch_size’]<br>
self.stride = conf[‘stride’]<br>
datainfo = conf[‘datainfo’]</p>
<pre><code>    Info = h5py.File(datainfo, 'r')
    index = Info['index'][:, int(exp_id) % 1000]
    ref_ids = Info['ref_ids'][0, :]
    test_ratio = conf['test_ratio']
    train_ratio = conf['train_ratio']
    trainindex = index[:int(train_ratio * len(index))]
    testindex = index[int((1-test_ratio) * len(index)):]
    train_index, val_index, test_index = [],[],[]
    for i in range(len(ref_ids)):
        train_index.append(i) if (ref_ids[i] in trainindex) else \
            test_index.append(i) if (ref_ids[i] in testindex) else \
                val_index.append(i)
    if status == 'train':
        self.index = train_index
        print("# Train Images: {}".format(len(self.index)))
        print('Ref Index:')
        print(trainindex)
    if status == 'test':
        self.index = test_index
        print("# Test Images: {}".format(len(self.index)))
        print('Ref Index:')
        print(testindex)
    if status == 'val':
        self.index = val_index
        print("# Val Images: {}".format(len(self.index)))

    self.mos = Info['subjective_scores'][0, self.index]
    self.mos_std = Info['subjective_scoresSTD'][0, self.index]
    im_names = [Info[Info['im_names'][0, :][i]][()].tobytes()\
                    [::2].decode() for i in self.index]
    
    self.patches = ()
    self.label = []
    self.label_std = []
    for idx in range(len(self.index)):
        # print("Preprocessing Image: {}".format(im_names[idx]))
        im = self.loader(os.path.join(im_dir, im_names[idx]))

        patches = NonOverlappingCropPatches(im, self.patch_size, self.stride)
        if status == 'train':
            self.patches = self.patches + patches #
            for i in range(len(patches)):
                self.label.append(self.mos[idx])
                self.label_std.append(self.mos_std[idx])
        else:
            self.patches = self.patches + (torch.stack(patches), ) #
            self.label.append(self.mos[idx])
            self.label_std.append(self.mos_std[idx])

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

def __getitem__(self, idx):
    return self.patches[idx], (torch.Tensor([self.label[idx]]), torch.Tensor([self.label_std[idx]]))
</code></pre>
<p>n this is the dataloader</p>
<p>def get_data_loaders(config, train_batch_size, exp_id=0):<br>
train_dataset = IQADataset(config, exp_id, ‘train’)<br>
train_loader = torch.utils.data.DataLoader(train_dataset,<br>
batch_size=train_batch_size,<br>
shuffle=True,<br>
num_workers=4)</p>
<pre><code>val_dataset = IQADataset(config, exp_id, 'val')
val_loader = torch.utils.data.DataLoader(val_dataset)

if config['test_ratio']:
    test_dataset = IQADataset(config, exp_id, 'test')
    test_loader = torch.utils.data.DataLoader(test_dataset)

    return train_loader, val_loader, test_loader

return train_loader, val_loader'''
</code></pre>

username: jyothi_sri
cooked: <p>can you help me out , this is the class for Dataset n dataloader</p>

username: jyothi_sri
cooked: <p><a class="mention" href="/u/srishti-git1110">@srishti-git1110</a> n <a class="mention" href="/u/ptrblck">@ptrblck</a>  please help me</p>

username: ptrblck
cooked: <p>Both of us have explained where the error is coming from and how to narrow it down.<br>
You’ve followed up with a code snippet which is not executable and didn’t respond to any suggestions how to narrow it down, so I’m unsure how else we can help.</p>

username: jyothi_sri
cooked: <p>Oh i m sorry i was busy n came back to work yesterday only so couldn’t respond .This is the data loader in the code , i just have changed it to RGB<br>
<strong>def default_loader(path):</strong><br>
**    return Image.open(path).convert(‘L’)**<br>
and i changed it to RGB<br>
<strong>def default_loader(path):</strong><br>
**    return Image.open(path).convert(‘RGB’)**</p>

username: parthshah231
cooked: <p>For your <code>DataLoader</code> assuming your <code>__getitem__()</code> call returns <code>List[Tensor, Tensor]</code> try this out:<br>
<code>next(iter(DataLoader))[0].shape</code> it should give you <code>[b, c, h, w]</code></p>
<p>b → batch_size<br>
c → number of channels<br>
h → height<br>
w → width</p>
<p>and then if you are getting <code>c = 1</code> you can further debug your <code>__getitem__()</code> as to see why<br>
Hope this helped.</p>

username: jyothi_sri
cooked: <p><a class="mention" href="/u/parthshah231">@parthshah231</a>  thank u  , i will try it.</p>