小编Dan*_* Le的帖子

PyTorch ValueError:目标和输入必须具有相同数量的元素

我对 PyTorch 有点陌生,但我试图了解在计算损失函数时目标和输入的大小在 torch.nn.BCELoss() 中是如何工作的。

import torch
import torch.nn as nn
from torch.autograd import Variable

time_steps = 15
batch_size = 3
embeddings_size = 100
num_classes = 2

model = nn.LSTM(embeddings_size, num_classes)
input_seq = Variable(torch.randn(time_steps, batch_size, embeddings_size))
lstm_out, _ = model(input_seq)
last_out = lstm_out[-1]
print(last_out)

loss = nn.BCELoss()
target = Variable(torch.LongTensor(batch_size).random_(0, num_classes))
print(target)
err = loss(last_out.long(), target)
err.backward()
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Warning (from warnings module):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/torch/nn/functional.py", line 767
"Please ensure they have the same size.".format(target.size(), input.size()))

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/torch/nn/functional.py", line 770, in binary_cross_entropy …
Run Code Online (Sandbox Code Playgroud)

python-3.x lstm pytorch

4
推荐指数
1
解决办法
1万
查看次数

标签 统计

lstm ×1

python-3.x ×1

pytorch ×1