RuntimeError: The size of tensor a (26) must match the size of tensor b (4) at non-singleton dimension 1

username: ReemY
cooked: <p>Hello All,</p>
<p>I am a beginner in Pytorch, i am having the following error after using a multilabel output:<br>
“RuntimeError: The size of tensor a (26) must match the size of tensor b (4) at non-singleton dimension 1”</p>
<p>in this line:<br>
correct += (pred.argmax(1) == y).type(torch.float).sum().item()</p>
<p>i reached a dead end, i can’t understand the issue, and tried different solutions found in the Pytorch forum as it is a common error.<br>
Please help.</p>
<p>The size of the input data is [128, 2000], and the size of the labelled data is [128,4]. The data is numeric.</p>
<p>My code is below:</p>
<h1>
<a name="define-model-loss-and-optimizer-1" class="anchor" href="#define-model-loss-and-optimizer-1"></a>Define model, loss and optimizer</h1>
<p>class NeuralNetwork(nn.Module):<br>
def <strong>init</strong>(self):<br>
super(NeuralNetwork, self).<strong>init</strong>()<br>
<span class="hashtag">#self</span>.flatten = nn.Flatten()<br>
self.linear_relu_stack = nn.Sequential(<br>
nn.Linear(D_in, H),<br>
nn.ReLU(),<span class="hashtag">#rectified</span> linear unit activation function<br>
nn.Linear(H, H),<br>
nn.ReLU(),<br>
nn.Linear(H, H),<br>
nn.ReLU(),<br>
nn.Linear(H, D_out),<br>
nn.Softmax() )</p>
<pre><code>def forward(self, x):
    #x = self.flatten(x)
    x = self.linear_relu_stack(x)
    logits = nn.functional.softmax(x)
    
    return logits
</code></pre>
<p>model = NeuralNetwork()</p>
<p>loss_fn = torch.nn.MSELoss(reduction=‘sum’)<br>
<span class="hashtag">#loss_fn</span> = nn.CrossEntropyLoss()<br>
<span class="hashtag">#optimizer</span> = torch.optim.Adam(model.parameters(), lr=learning_rate)<br>
<span class="hashtag">#optimizer</span> = torch.optim.SGD(model.parameters(), lr=learning_rate)<br>
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9)<br>
losses=[]</p>
<p>def train_loop(dataloader, model, loss_fn, optimizer):<br>
size = len(dataloader.dataset)<br>
for batch, (X, y) in enumerate(dataloader):<br>
# Compute prediction and loss<br>
pred = model(X)<br>
loss = loss_fn(pred, y)<br>
losses.append(loss.item())<br>
print(f" pred: {pred} , y: {y}")</p>
<pre><code>    # Backpropagation
    optimizer.zero_grad()# zero the gradient buffers
    loss.backward()
    optimizer.step()# Does the update

    if batch % 100 == 0:
        loss, current = loss.item(), batch * len(X)
        print(f"loss: {loss:&gt;7f}  [{current:&gt;5d}/{size:&gt;5d}] ")
</code></pre>
<p>def test_loop(dataloader, model, loss_fn):<br>
size = len(dataloader.dataset)<br>
num_batches = len(dataloader)<br>
test_loss, correct = 0, 0</p>
<pre><code>with torch.no_grad():
    for X, y in dataloader:
        pred = model(X)

        print(f" pred: {pred} , y: {y}")

        test_loss += loss_fn(pred, y).item()
        pred.size
        y.size
        correct += (pred.argmax(1) == y).type(torch.float).sum().item()
        print(f" pred: {pred} , y: {y}")


test_loss /= num_batches
correct /= size
print(f"Test Error: \n Accuracy: {(100*correct):&gt;0.1f}%, Avg loss: {test_loss:&gt;8f} \n")
</code></pre>
<p>for t in range(epochs):<br>
print(f"Epoch {t+1}\n-------------------------------")<br>
train_loop(train_dataloader, model, loss_fn, optimizer)<br>
test_loop(test_dataloader, model, loss_fn)</p>
<p>print(“Done!”)</p>

username: eqy
cooked: <p>I would start by checking if the shape of the model output is expected (if it’s a classification task, it might look something like [batch_size, num_classes]).</p>