Incorrect size for labels and predictions for loss fn (embedding layer))

Hindy_Yuen: <p>I am new to pytorch. I am trying to implement a simple model with the embedding layer.</p>
<p>I am using the SMS spam dataset.</p>
<p>I have already converted and padded the text data into indexes and built a bacth_generator function which yield batches of targets and inputs in tensor.</p>
<p>when I am trying run the training loop, it said:</p>
<p>ValueError: Using a target size (torch.Size([1])) that is different to the input size (torch.Size([1, 83, 7405])) is deprecated. Please ensure they have the same size.</p>
<p>It seems the size of the predictions from the model is not the same as the size of the target batches. Hence, it cannot calculate the loss.</p>
<p>What should I do if they are the same size?</p>
<p>Model:</p>
<p>class NLP(nn.Module):<br>
def <strong>init</strong>(self, embedding_size=50, vocab_size=vocabSize):<br>
super(NLP, self).<strong>init</strong>()<br>
self.embeddings = nn.Embedding(vocabSize, embedding_size)<br>
self.linear1 = nn.Linear(embedding_size, 100)</p>
<pre><code>def forward(self, inputs):
    lookup_embeds = self.embeddings(inputs)
    out = self.linear1(lookup_embeds)
    out = F.log_softmax(out)
    return out
</code></pre>
<p>Training loop:</p>
<p>losses = []<br>
loss = nn.BCELoss()<br>
model = NLP(vocab_size=vocabSize, embedding_size=50)<br>
optimizer = optim.SGD(model.parameters(), lr=0.001)</p>
<p>for epoch in range(10):<br>
total_loss = 0<br>
for l, t in bacth_generator(train, 32):<br>
model.zero_grad()<br>
prediction = model(t)<br>
output = loss(prediction, l)</p>
<p>ValueError: Using a target size (torch.Size([32])) that is different to the input size (torch.Size([32, 83, 100])) is deprecated. Please ensure they have the same size.</p>

ptrblck: <p><code>nn.BCELoss</code> expects the model output and target to have the same shape.<br>
Based on your code snippet it seems that the model output has two additional dimensions, so could you explain what the model is supposed to predict and how this would fit the target shape?<br>
Also, use <code>torch.sigmoid</code>, as <code>nn.BCELoss</code> expects probabilities coming from the model or (better) remove <code>F.log_softmax</code> and use <code>nn.BCEWithLogitsLoss</code> for more numerical stability.</p>

Hindy_Yuen: <p>Thank you for your reply. This is supposed to be binary classification model. I am trying to learn how to implement an embedding layer. As for how to fit the target shape, this is exactly what I want to know!! Why the prediction become 3 dimensional ?</p>

Hindy_Yuen: <p>Besides,</p>
<ol>
<li>
<p>Is there anything or concept that I should remember as a beginner when implementing pytorch model ?</p>
</li>
<li>
<p>Is there any tutorial or learning materials that you recommend ?</p>
</li>
</ol>

ptrblck: <aside class="quote no-group" data-username="Hindy_Yuen" data-post="3" data-topic="132337">
<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/hindy_yuen/48/42323_2.png" class="avatar"> Hindy_Yuen:</div>
<blockquote>
<p>Why the prediction become 3 dimensional ?</p>
</blockquote>
</aside>
<p>I guess because you are feeding a 2D input to the model as seen here:</p>
<pre data-code-wrap="python"><code class="lang-python">embeddings = nn.Embedding(100, 10)
linear1 = nn.Linear(10, 100)

x = torch.randint(0, 100, (2, 3))
out = embeddings(x)
print(out.shape) # torch.Size([2, 3, 10])
out = linear1(out)
print(out.shape) # torch.Size([2, 3, 100])
</code></pre>
<p>You can print the shapes of all tensors in the <code>forward</code> method to check it manually.</p>
<p>Depending on your knowledge about ML/DL you might want to check out a course (e.g. FastAI) or just take a look at the <a href="https://pytorch.org/tutorials/">tutorials</a>. It’s a bit hard to recommend anything else without knowing what you are struggling with.</p>

Hindy_Yuen: <p>I have noticed that other models will have layers like torch.max() and torch.sum() right after the nn.Linear() layer. Which makes the 3D output from the previous layer become 2D again, then I am able to use it with the labels to calculate the loss.</p>
<p>So now my question has become, why would someone pick torch.max() or torch.sum() or other layers ? Is that part of the hyperparameter tuning procedure ?</p>

ptrblck: <p>I think it depends on your use case and what the inputs represent.<br>
A 2D input using indices (as is used in my example) could represent e.g. a temporal signal, where each time step is assigned to an index. This approach could be used e.g. if you are mapping words to indices and are trying to pass “sequences of words” (i.e. sentences) to the model.<br>
I’m not familiar with your use case and thus also don’t know what the expected predictions are, e.g. a per-word or sentence classification etc.<br>
In case you are trying to reproduce a specific approach explained in a paper, I would assume the authors might have explained their approach there.</p>