I am trying to build multilayer perceptron. I do not know why i am get this error please help (mat1 and mat2 shapes cannot be multiplied (64x784 and 16875x1020)). I am using a dataset of people classification from kaggle

ANAS_KHAN: <p>tranformed =transforms.Compose([transforms.Resize((75,75)) ,<br>
transforms.ToTensor()])</p>
<p>train_path =‘C:/Users/anask/Desktop/AI/NN/data/train’</p>
<p>test_path = ‘C:/Users/anask/Desktop/AI/NN/data/val’</p>
<p>train_loader=DataLoader(torchvision.datasets.ImageFolder(train_path,transform=tranformed) , batch_size= 14 , shuffle=True)<br>
test_loader=DataLoader(torchvision.datasets.ImageFolder(test_path,transform=tranformed) , batch_size=14 ,shuffle=True)</p>
<p>class NN(nn.Module):<br>
def <strong>init</strong>(self,num_classes=5):<br>
super(NN,self).<strong>init</strong>()<br>
self.l1=nn.Linear(3<em>75</em>75 , 1020)<br>
self.relu= nn.ReLU()<br>
self.l2 = nn.Linear(255,5)</p>
<p>def forward(self,x):<br>
out= x.view(x.size(0), -1)<br>
out =self.l1(x)<br>
out = self.relu(out)</p>
<p>return out</p>

KFrank: <p>Hi Anas!</p>
<aside class="quote no-group quote-modified" data-username="ANAS_KHAN" data-post="1" data-topic="133632" data-full="true">
<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/anas_khan/48/33224_2.png" class="avatar"> ANAS_KHAN:</div>
<blockquote>
<pre data-code-wrap="python"><code class="lang-python">self.l1=nn.Linear(3*75*75 , 1020)
...
out= x.view(x.size(0), -1)
out =self.l1(x)
</code></pre>
</blockquote>
</aside>
<p>Your model expects an input with <code>3 * 75 * 75 = 16875</code> features, but<br>
you are only passing in <code>784</code> features.</p>
<p>Print out the shape of the tensor that you are passing into your model.<br>
I expect that it will be <code>[64, 28, 28]</code> (where you are passing in a batch<br>
of 64 28x28 images that <code>x.view(x.size(0), -1)</code> turns into a tensor<br>
of shape <code>[64, 784]</code>).</p>
<p>Best.</p>
<p>K. Frank</p>

ANAS_KHAN: <p>know I am getting this error</p>
<p>class NN(nn.Module):<br>
def <strong>init</strong>(self,num_classes):<br>
super(NN,self).<strong>init</strong>()</p>
<pre><code>    self.l1=nn.Linear(3*75*75, 50)
    self.relu= nn.ReLU()
    self.l2 = nn.Linear(50,5)

def forward(self,x):
    
    out= x.view(x.size(0), -1)
    
    out =self.l1(x)
    out = self.relu(out)
    out=self.l2(out)
    return out
</code></pre>
<p>model=NN(num_classes=5)<br>
optimizer=Adam(model.parameters(),lr=0.001,weight_decay=0.0001)<br>
loss_function = nn.CrossEntropyLoss()<br>
num_epochs=10<br>
train_count=len(glob.glob(train_path+’/<strong>/*.jpg’))<br>
test_count=len(glob.glob(test_path+’/</strong>/*.jpg’))</p>
<p>print_every = 5</p>
<h1>
<a name="initialize-the-loss-variables-1" class="anchor" href="#initialize-the-loss-variables-1"></a>Initialize the loss variables</h1>
<p>running_loss = 0<br>
train_losses, test_losses = [], []</p>
<h1>
<a name="track-the-current-training-step-start-at-0-2" class="anchor" href="#track-the-current-training-step-start-at-0-2"></a>Track the current training step, start at 0</h1>
<p>steps = 0<br>
for epochs in range(num_epochs):<br>
epochs += 1<br>
model.train()<br>
for i, (images,labels) in enumerate(train_loader):<br>
steps += 1<br>
images=images.view(images.size(0),-1)<br>
optimizer.zero_grad()<br>
print(images.shape)<br>
output=model(images)</p>
<pre><code>    loss=loss_function(output,labels)
    loss.backward()
    optimizer.step()
    running_loss += loss.item()

  # Every 5 steps, evaluate the model
    if steps % print_every == 0:
        
        # Initialize loss and accuracy
        test_loss = 0
        accuracy = 0
        # Start the model evaluation
        model.eval()

        # Refine the accuracy of the prediction without updating the gradients
        with torch.no_grad():
            
            
             # Load in all of the image inputs and labels from the TEST loader 
            for i, (inputs, labels) in enumerate(test_loader):
                
                 # Load the inputs and labels to the already selected device
                images, labels = images, labels
               # images=images.reshape(images.shape[0],-1)
                images=images.view(images.size(0),-1)
                
                # Pass the images through the model, return the log probabilities of each label
                output = model(images)
                print(f"images: {images.shape}" )
                # Run the log probabilities through the criterion to get the output graph
                loss = loss_function(output, labels)
                # Add the actual loss number to the running loss total for the test batch
                test_loss += loss.item()
                # Return a new tensor with the true probabilities
                ps = torch.exp(output)
                # Return the largest probability and class of the new tensor along a given dimension
                top_p, top_class = ps.topk(1, dim=1)
                # Reshape the tensor to match the same shape as the top class
                equals = top_class == labels.view(*top_class.shape)
                # Compute the accuracy and add it to the running accuracy count for the test batch
                accuracy += torch.mean(equals.type(torch.FloatTensor)).item()
            # Append the training and testing losses
        train_losses.append(running_loss/len(train_loader))
        test_losses.append(test_loss/len(test_loader))  
        # Display the accuracy of the prediction with 3 digits in the fractional part of the decimal
        print(f"\n     Epoch {epoch}/{epochs}: "
           f"Train loss: {running_loss/print_every:.3f}.. "
           f"Test loss: {test_loss/len(test_loader):.3f}.. "
           f"Test accuracy: {accuracy/len(test_loader):.3f}\n")
          # Train the model
        running_loss = 0
        model.train()

     # After 5 training steps, start the next epoch
     # Break here in case the trainloader has remaining data
        break
  ..............................
   output......................
</code></pre>
<h2>
<a name="torchsize14-16875-torchsize14-16875-torchsize14-16875-torchsize14-16875-torchsize14-16875-images-torchsize14-16875-images-torchsize14-16875-3" class="anchor" href="#torchsize14-16875-torchsize14-16875-torchsize14-16875-torchsize14-16875-torchsize14-16875-images-torchsize14-16875-images-torchsize14-16875-3"></a>torch.Size([14, 16875])<br>
torch.Size([14, 16875])<br>
torch.Size([14, 16875])<br>
torch.Size([14, 16875])<br>
torch.Size([14, 16875])<br>
images: torch.Size([14, 16875])<br>
images: torch.Size([14, 16875])</h2>
<p>ValueError                                Traceback (most recent call last)<br>
 in <br>
72                     print(f"images: {images.shape}" )<br>
73                     # Run the log probabilities through the criterion to get the output graph<br>
—&gt; 74                     loss = loss_function(output, labels)<br>
75                     # Add the actual loss number to the running loss total for the test batch<br>
76                     test_loss += loss.item()</p>
<p>~\Miniconda3\lib\site-packages\torch\nn\modules\module.py in _call_impl(self, *input, **kwargs)<br>
725             result = self._slow_forward(*input, **kwargs)<br>
726         else:<br>
 → 727             result = self.forward(*input, **kwargs)<br>
728         for hook in itertools.chain(<br>
729                 _global_forward_hooks.values(),</p>
<p>~\Miniconda3\lib\site-packages\torch\nn\modules\loss.py in forward(self, input, target)<br>
959<br>
960     def forward(self, input: Tensor, target: Tensor) → Tensor:<br>
 → 961         return F.cross_entropy(input, target, weight=self.weight,<br>
962                                ignore_index=self.ignore_index, reduction=self.reduction)<br>
963</p>
<p>~\Miniconda3\lib\site-packages\torch\nn\functional.py in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction)<br>
2466     if size_average is not None or reduce is not None:<br>
2467         reduction = _Reduction.legacy_get_string(size_average, reduce)<br>
 → 2468     return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)<br>
2469<br>
2470</p>
<p>~\Miniconda3\lib\site-packages\torch\nn\functional.py in nll_loss(input, target, weight, size_average, ignore_index, reduce, reduction)<br>
2259<br>
2260     if input.size(0) != target.size(0):<br>
 → 2261         raise ValueError(‘Expected input batch_size ({}) to match target batch_size ({}).’<br>
2262                          .format(input.size(0), target.size(0)))<br>
2263     if dim == 2:</p>
<p>ValueError: Expected input batch_size (14) to match target batch_size (11).</p>

ANAS_KHAN: <p>please look into it. I do not understand it why this error</p>

KFrank: <p>Hi Anas!</p>
<aside class="quote no-group quote-modified" data-username="ANAS_KHAN" data-post="3" data-topic="133632" data-full="true">
<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/anas_khan/48/33224_2.png" class="avatar"> ANAS_KHAN:</div>
<blockquote>
<p>know I am getting this error<br>
…<br>
ValueError: Expected input batch_size (14) to match target batch_size (11).</p>
</blockquote>
</aside>
<p>Does this help?</p>
<pre><code class="lang-plaintext">&gt;&gt;&gt; torch.__version__
'1.9.0'
&gt;&gt;&gt; torch.nn.CrossEntropyLoss() (torch.randn (14, 3), torch.randint (3, (11,)))
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  File "&lt;path_to_pytorch_install&gt;\torch\nn\modules\module.py", line 1051, in _call_impl
    return forward_call(*input, **kwargs)
  File "&lt;path_to_pytorch_install&gt;\torch\nn\modules\loss.py", line 1121, in forward
    ignore_index=self.ignore_index, reduction=self.reduction)
  File "&lt;path_to_pytorch_install&gt;\torch\nn\functional.py", line 2824, in cross_entropy
    return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
ValueError: Expected input batch_size (14) to match target batch_size (11).
</code></pre>
<p>Best.</p>
<p>K. Frank</p>