Dan*_* Le 4 python-3.x lstm pytorch
我对 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
"!= input nelement ({})".format(target.nelement(), input.nelement()))
ValueError: Target and input must have the same number of elements. target nelement (3) != input nelement (6)
Run Code Online (Sandbox Code Playgroud)
这个错误肯定来自last_out(大小3x2)和目标(大小3)的不同大小。所以我的问题是如何将 last_out 转换为类似于目标(大小为 3 且仅包含 0 和 1)的内容来计算损失函数?
的想法nn.BCELoss()是实现以下公式:
这两个o和t是任意的(但一样!)的张量大小和i简单的指标两个张量的每个元素来计算上面的总和。
通常,nn.BCELoss()用于分类设置:o并且i将是维度矩阵N x D。N将是您的数据集或小批量中的观察数。D如果您只尝试对单个属性进行分类,则为 1,如果您尝试对多个属性进行分类,则大于 1。t,目标矩阵,将只包含 0 和 1,对于每个属性,只有两个类(这就是二元交叉熵损失中的二元来源)。o将持有您将每个观察的每个属性分配给第 1 类的概率。
现在,在您上面的设置中,不清楚您正在考虑多少类以及有多少属性适合您。如果target您的model. 如果有两个属性,你的就不targets完整了!如果有多个类,您应该使用torch.nn.CrossEntropyLoss而不是torch.nn.BCELoss().
顺便说一句,为了数值稳定性,通常需要使用torch.nn.BCEWithLogitsLoss而不是torch.nn.BCELoss()跟随nn.Sigmoid()某些输出。
| 归档时间: |
|
| 查看次数: |
10445 次 |
| 最近记录: |