【发布时间】:2018-05-15 14:47:14
【问题描述】:
我对 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()
我收到以下错误:
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
"!= input nelement ({})".format(target.nelement(), input.nelement()))
ValueError: Target and input must have the same number of elements. target nelement (3) != input nelement (6)
这个错误肯定来自last_out (size 3x2) 和target (size 3) 的大小不同。所以我的问题是如何将 last_out 转换为目标(大小为 3,仅包含 0 和 1)来计算损失函数?
【问题讨论】:
标签: python-3.x lstm pytorch