python - 在pytorch中计算困惑度

标签 python nlp pytorch language-model

我刚刚使用 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)

如果您想获得每个单词的困惑度,那么您只需要注意这一点,那么您也需要每个单词的损失。

这是一个语言模型的简洁示例,它也可以计算输出的困惑度,看起来可能很有趣:

https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/02-intermediate/language_model/main.py#L30-L50

关于python - 在pytorch中计算困惑度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59209086/

相关文章:

python - 过滤掉出现次数少于最小阈值的元素

python - Python 中一个模式的多次出现

math - 向量数量不同的两个图节点之间的余弦相似度计算

python-3.x - Pytorch:图像标签

python - 在 matplotlib 图中正确显示 x 轴标签

machine-learning - 创建自学习情感词典

python - 计算字符串中尾随换行符的数量

python - 在 GPU 中进行 60 分钟 Blitz 训练 PyTorch 分类器时出错

machine-learning - 如何在PYTORCH中进行2层嵌套FOR循环?

python - 将图片与 QGraphicsItem 关联