ValueError: Using a target size (torch.Size([32])) that is different to the input size (torch.Size([32, 2])) is deprecated. Please ensure they have the same size

Tejas1020: <p>This is the Train and Test Code where i guess i am getting the error please help me figuring out this.</p>
<h1><a name="train-and-test-engine-1" class="anchor" href="#train-and-test-engine-1"></a>Train and Test Engine</h1>
<p>from tqdm.auto import tqdm</p>
<p>def train_step(model : torch.nn,<br>
dataloader: torch.utils.data.DataLoader,<br>
loss_fn: torch.nn.Module,<br>
optimizer: torch.optim.Optimizer,<br>
device:torch.device):</p>
<p>model.train()<br>
train_loss, train_acc = 0 , 0</p>
<p>for batch, (X,y) in enumerate(dataloader):<br>
X,y = X.to(device), y.to(device)<br>
# feed forward<br>
y_pred = model(X)<br>
# calculate loss<br>
loss = loss_fn(y_pred, y)<br>
train_loss += loss.item()<br>
# Optimizer<br>
optimizer.zero_grad()<br>
# loss backward(backpropagation)<br>
loss.backward()<br>
optimizer.step()<br>
# calculate accuracy<br>
y_pred_class = torch.argmax(torch.softmax(y_pred, dim = 1), dim = 1)<br>
train_acc += (y_pred_class == y).sum().item() / len(y_pred)</p>
<p>train_loss = train_loss / len(dataloader)<br>
train_acc = train_acc / len(dataloader)<br>
return train_loss, train_acc</p>
<p>def test_step(model: torch.nn.Module,<br>
dataloader: torch.utils.data.DataLoader,<br>
loss_fn: torch.nn.Module,<br>
device: torch.device):<br>
model.eval()<br>
test_loss, test_acc = 0 , 0</p>
<p>with torch.inference_mode():<br>
for batch, (X , y) in enumerate(dataloader):<br>
X,y = X.to(device) , y.to(device)<br>
# feed forward<br>
test_pred_logits = model(X)<br>
# calculate loss<br>
loss = loss_fn(test_pred_logits, y)<br>
test_loss += loss.item()<br>
# calculate acccuracy<br>
test_pred_labels = test_pred_logits.argmax(dim=1)<br>
test_acc += ((test_pred_labels == y).sum().item()/len(test_pred_labels))</p>
<p>test_loss = test_loss / len(dataloader)<br>
test_acc = test_acc / len(dataloader)<br>
return test_loss, test_acc</p>
<p>def train(model: torch.nn.Module,<br>
train_dataloader: torch.utils.data.DataLoader,<br>
test_dataloader: torch.utils.data.DataLoader,<br>
optimizer: torch.optim.Optimizer,<br>
loss_fn: torch.nn.Module,<br>
epochs: int,<br>
device: torch.device):<br>
results = {“train_loss”:<span class="chcklst-box fa fa-square-o fa-fw"></span>,<br>
“train_acc”:<span class="chcklst-box fa fa-square-o fa-fw"></span>,<br>
“test_loss”:<span class="chcklst-box fa fa-square-o fa-fw"></span>,<br>
“test_acc”:<span class="chcklst-box fa fa-square-o fa-fw"></span><br>
}</p>
<p>model.to(device)</p>
<p>for epoch in tqdm(range(epochs)):<br>
train_loss, train_acc = train_step(model = model,<br>
dataloader = train_dataloader,<br>
loss_fn = loss_fn,<br>
optimizer = optimizer,<br>
device = device)<br>
test_loss, test_acc = test_step(model = model,<br>
dataloader = test_dataloader,<br>
loss_fn = loss_fn,<br>
device = device)<br>
# print results epoch<br>
print(f"Epoch: {epoch+1} | train_acc: {train_acc:.4f} | train_loss: {train_loss:.4f} | test_acc: {test_acc:.4f} | test_loss: {test_loss:.4f}")<br>
# update results<br>
results[“train_acc”].append(train_acc)<br>
results[“train_loss”].append(train_loss)<br>
results[“test_acc”].append(test_acc)<br>
results[“test_loss”].append(test_loss)</p>
<p>return results</p>

KFrank: <p>Hi Tejas!</p>
<aside class="quote no-group" data-username="Tejas1020" data-post="1" data-topic="189346" 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/tejas1020/48/60265_2.png" class="avatar"> Tejas1020:</div>
<blockquote>
<p>please help me figuring out this.</p>
</blockquote>
</aside>
<p>You are most likely passing an <code>input</code> and <code>target</code> of differing sizes to<br>
<code>BCELoss</code>.  (Similar issues arise for the same reason with other losses<br>
such as <code>BCEWithLogitsLoss</code> and <code>MSELoss</code>, but you would get slightly<br>
different error messages.)</p>
<p>(If you do this, <a href="https://pytorch.org/docs/2.0/notes/broadcasting.html" rel="noopener nofollow ugc">broadcasting</a> can occur under the hood of the loss function,<br>
leading to unexpectedly incorrect results.)</p>
<p>Make sure that you understand the semantics of <code>BCELoss</code> and adjust your<br>
code accordingly.</p>
<p>If you are still having issues, please make a super-simplified test case – use<br>
just a randomly-generated <code>input</code> and <code>target</code> and pass them directly to your<br>
loss function – and post a fully-self-contained, runnable script that illustrates<br>
your issue together with its output.</p>
<p>As an aside, for reasons of numerical stability, don’t use <code>BCELoss</code> – use<br>
<code>BCEWithLogitsLoss</code> instead, adjusting your code as necessary (presumably<br>
by removing a <code>sigmoid()</code> at the end of your model).</p>
<p>Best.</p>
<p>K. Frank</p>

Tejas1020: <p>I applied all above changes but still Don’t Know where getting error</p>

KFrank: <p>Hi Tejas!</p>
<aside class="quote no-group" data-username="Tejas1020" data-post="3" data-topic="189346" 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/tejas1020/48/60265_2.png" class="avatar"> Tejas1020:</div>
<blockquote>
<p>Don’t Know where getting error</p>
</blockquote>
</aside>
<p>I don’t know either.</p>
<p>Could you post a truly-minimal, fully-self-contained, runnable script that<br>
reproduces your issue?</p>
<p>Best.</p>
<p>K. Frank</p>