我刚刚使用 pytorch 训练了 LSTM 语言模型。类的主体是这样的:
class LM(nn.Module):
def __init__(self, n_vocab,
seq_size,
embedding_size,
lstm_size,
pretrained_embed):
super(LM, self).__init__()
self.seq_size = seq_size
self.lstm_size = lstm_size
self.embedding = nn.Embedding.from_pretrained(pretrained_embed, freeze = True)
self.lstm = nn.LSTM(embedding_size,
lstm_size,
batch_first=True)
self.fc = nn.Linear(lstm_size, n_vocab)
def forward(self, x, prev_state):
embed = self.embedding(x)
output, state = self.lstm(embed, prev_state)
logits = self.fc(output)
return logits, state
现在我想编写一个函数,根据经过训练的语言模型(一些分数,如困惑度等)来计算句子的好坏程度。
我有点困惑,我不知道该如何计算。
类似的示例会有很大用处。
最佳答案
使用交叉熵损失时,您只需使用指数函数 torch.exp()
计算损失的困惑度。
(pytorch cross-entropy also uses the exponential function resp. log_n)
所以这只是一些虚拟示例:
import torch
import torch.nn.functional as F
num_classes = 10
batch_size = 1
# your model outputs / logits
output = torch.rand(batch_size, num_classes)
# your targets
target = torch.randint(num_classes, (batch_size,))
# getting loss using cross entropy
loss = F.cross_entropy(output, target)
# calculating perplexity
perplexity = torch.exp(loss)
print('Loss:', loss, 'PP:', perplexity)
就我而言,输出是:
Loss: tensor(2.7935) PP: tensor(16.3376)
如果您想获得每个单词的困惑度,那么您只需要注意这一点,那么您也需要每个单词的损失。
这是一个语言模型的简洁示例,它也可以计算输出的困惑度,看起来可能很有趣:
关于python - 在pytorch中计算困惑度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59209086/