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

Niraja: <p>I am facing this problem at the time of testing. While training the data it works fine, but at the time of testing the data it arise this error.<br>
‘’’<br>
class test_dataset(Dataset):<br>
def <strong>init</strong>(self, age_label_test, gen_label_test, img_test):<br>
self.age_label_test = np.array(age_label_test)<br>
self.gen_label_test = np.array(gen_label_test)<br>
self.img_test = np.array(img_test)</p>
<p>def <strong>len</strong>(self):<br>
return len(self.img_test)</p>
<p>def <strong>getitem</strong>(self, index):<br>
age_label_test = self.age_label_test[index]<br>
gen_label_test = self.gen_label_test[index]</p>
<pre><code> img_test = self.img_test[index].reshape(48,48,1)
 #img = self.transform(X_train)

 return img_test, age_label_test, gen_label_test
</code></pre>
<p>test_data = test_dataset(y_age_test[:], y_gender_test[:],<br>
X_test[:])</p>
<p>test_dataloader = DataLoader(test_data, batch_size = 50, shuffle = True)<br>
‘’’</p>
<p>‘’’<br>
import torch.nn as nn<br>
from torchsummary import summary<br>
import timm<br>
from timm.models.layers.classifier import ClassifierHead<br>
import torch.nn.functional as F</p>
<h1><a name="building-model-1" class="anchor" href="#building-model-1"></a>Building Model</h1>
<p>class Net(nn.Module):<br>
def <strong>init</strong>(self):<br>
super(Net, self).<strong>init</strong>()</p>
<pre><code>    self.conv1 = nn.Conv2d(in_channels = 1, out_channels = 32, kernel_size = 3, padding=1, stride=1)
    self.relu = nn.ReLU()
    self.maxpool = nn.MaxPool2d(kernel_size = 2)
    
    
    self.conv2 = nn.Conv2d(in_channels = 32, out_channels = 64, kernel_size = 3, padding=1, stride=1)
    
    self.conv3 = nn.Conv2d(in_channels = 64, out_channels = 128, kernel_size = 3, padding=1, stride=1)

    self.conv4 = nn.Conv2d(in_channels = 128, out_channels = 256, kernel_size = 3, padding=1, stride=1)
    
    #nn.Flatten()
    
    self.fc1 = nn.Linear(in_features = 256*3*3, out_features = 1152)
    
    self.fc2 = nn.Linear(in_features = 1152, out_features = 512) 
    
    self.linear1 = nn.Linear(in_features = 512, out_features = age_features) # For age class output
    self.linear2 = nn.Linear(in_features = 512, out_features = gen_features)   # For gender class output
 
def forward(self, x):
    out = self.conv1(x)
    out = self.relu(out)
    out = self.maxpool(out)
    
    out = self.conv2(out)
    out = self.relu(out)
    out = self.maxpool(out)
    
    out = self.conv3(out)
    out = self.relu(out)
    out = self.maxpool(out)
    
    out = self.conv4(out)
    out = self.relu(out)
    out = self.maxpool(out)
    
    #print(out.shape)
    out = out.view(x.size(0),-1)
    out = F.relu(self.fc1(out))
    out = F.relu(self.fc2(out))
    label1 = self.linear1(out)                 # Age output
    label2 = self.linear2(out) # Gender output
    
    return {'label1': torch.softmax(label1,dim=1), 'label2': label2}
</code></pre>
<p>‘’’<br>
‘’’<br>
age_accuracy_list = <span class="chcklst-box fa fa-square-o fa-fw"></span><br>
gender_accuracy_list = <span class="chcklst-box fa fa-square-o fa-fw"></span><br>
validation_loss_list=<span class="chcklst-box fa fa-square-o fa-fw"></span></p>
<p>def test(model, criterion1, criterion2, test_dataloader, optimizer, epoch):</p>
<h1><a name="switch-the-model-to-evaluation-mode-2" class="anchor" href="#switch-the-model-to-evaluation-mode-2"></a>Switch the model to evaluation mode</h1>
<p>model.eval()<br>
correct_1 = 0<br>
correct_2 = 0<br>
total_1 = 0<br>
total_2 = 0<br>
valid_loss = 0</p>
<p>with torch.no_grad():</p>
<pre><code>for batch_idx, (data, target1, target2) in enumerate(test_dataloader):
  data, target1, target2 = data.to(device), target1.to(device), target2.to(device)
  
  data = data.requires_grad_()  # Load images(for accuracy)
  output = model(data.float())

  _, predicted1 = torch.max(output['label1'], 1)
  _, predicted2 = torch.max(output['label2'], 1)

  label1_hat = output['label1']
  label2_hat = output['label2']

  total_1 += target1.size(0)
  total_2 += target2.size(0)
  
  correct_1 += torch.sum(predicted1 == target1).item()
  correct_2 += torch.sum(predicted2 == target2).item()
  
  age_accuracy = 100 * correct_1 // total_1
  gender_accuracy = 100 * correct_2 // total_2

  # calculate loss
  loss1 = criterion1(label1_hat, target1)
  loss2 = criterion2(label2_hat, target2)
  loss = loss1+loss2
  valid_loss = valid_loss + ((1 / (batch_idx + 1)) * (loss.data - valid_loss))

print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f} \tAge_Accuracy: {} \tGender_Accuracy: {}'.format(
        epoch, train_loss, valid_loss, age_accuracy, gender_accuracy))
age_accuracy_list.append(age_accuracy)
gender_accuracy_list.append(gender_accuracy)
validation_loss_list.append(valid_loss)
return valid_loss, age_accuracy, gender_accuracy
</code></pre>
<p>‘’’<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/b/2/b21b0bf534c7572271e1f3207c8392b528b21976.png" data-download-href="https://discuss.pytorch.org/uploads/default/b21b0bf534c7572271e1f3207c8392b528b21976" title="image"><img src="https://discuss.pytorch.org/uploads/default/original/3X/b/2/b21b0bf534c7572271e1f3207c8392b528b21976.png" alt="image" data-base62-sha1="ppAW618dEBO9l6TSzTsuiCE9kSq" width="690" height="352" data-dominant-color="F6F5F6"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">1397×713 43.2 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>

ptrblck: <p>Based on the error message the input tensor might be in the channels-last memory layout during testing while channels-first is expected.<br>
I don’t know why the memory layout differs between training and testing, but you could <code>permute</code> the input via:</p>
<pre><code class="lang-python">x = x.permute(0, 3, 1, 2)
</code></pre>
<p>before passing it to the model.</p>