目前,我正在使用PyTorch实现连续的单词袋(CBOW)模型。但是,在实现交叉熵损失时,我面临着一些问题。下面是导致问题的部分代码:
for idx, sample in enumerate(self.train_data):
x = torch.tensor(sample[0], dtype=torch.long)
y = np.zeros(shape=(self.vocab_size)) # self.vocab_size = 85,000
y[int(sample[1])] = np.float64(1)
y = torch.tensor(y, dtype=torch.long)
if torch.cuda.is_available():
x = x.cuda()
y = y.cuda()
optimizer.zero_grad()
output = self.model(x) # output's shape is the same as self.vocab_size
loss = criterion(output, y)
loss.backward()
optimizer.step()
为了简单解释我的代码,我实现的model
基本上输出上下文数组的平均嵌入值,并执行线性投影,将它们投影成与词汇表大小相同的形状。然后我们通过一个softmax函数运行这个数组。
self.train_data
的内容基本上是(context, target_word)
对。y
是令牌的一个单一热编码数组。
我知道nn.CrossEntropyLoss
的第二个输入是C = # of classes
,但我不知道我的代码哪里出错了。词汇量是85,000,那么85,000级的词汇量不是吗?
如果我将输入更改为
loss = criterion(output, 85000)
我也犯了同样的错误:
*** RuntimeError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
我做错了什么,我应该如何理解PyTorch交叉熵损失的输入?
谢谢。
发布于 2019-11-18 11:04:40
我知道nn.CrossEntropyLoss的第二个输入是类的C=#,但我不知道我的代码哪里出错了。词汇量是85,000,那么85,000级的词汇量不是吗?
类的数量(nc)可能是85000,但也有批处理大小:
target = torch.randint (nc, (bs,))
目标表示真实值,而输出是从特定输入x的模型中得到的,在您的例子中是output = self.model(x)
。
在这里
loss = criterion(output, target)
您可以说输出是您目前从模型中得到的,目标是您在完成培训时应该得到的结果。
https://stackoverflow.com/questions/58891039
复制相似问题