【问题标题】:How to do Sentence Similarity with XLNet?如何用 XLNet 做句子相似度?
【发布时间】:2020-07-03 08:06:09
【问题描述】:

我想执行一个句子相似度任务并尝试了以下方法:

from transformers import XLNetTokenizer, XLNetModel
import torch
import scipy
import torch.nn as nn
import torch.nn.functional as F

tokenizer = XLNetTokenizer.from_pretrained('xlnet-large-cased')
model = XLNetModel.from_pretrained('xlnet-large-cased')

input_ids = torch.tensor(tokenizer.encode("Hello, my animal is cute", add_special_tokens=False)).unsqueeze(0)
outputs = model(input_ids)
last_hidden_states = outputs[0]

input_ids = torch.tensor(tokenizer.encode("I like your cat", add_special_tokens=False)).unsqueeze(0) 

outputs1 = model(input_ids)
last_hidden_states1 = outputs1[0]

cos = nn.CosineSimilarity(dim=1, eps=1e-6)
output = cos(last_hidden_states, last_hidden_states1)

但是,我收到以下错误:

RuntimeError: The size of tensor a (7) must match the size of tensor b (4) at non-singleton dimension 1

谁能告诉我,我做错了什么?有没有更好的方法?

【问题讨论】:

    标签: python nlp embedding cosine-similarity transformer


    【解决方案1】:

    你做错了几件事。

    1. add_special_tokens 应设置为 True。该模型使用<sep> 标记用于分离句子,<cls> 标记用于句子分类。由于训练测试数据不匹配,未使用导致奇怪行为的线索。

    2. outputs[0] 为您提供单成员 Python 元组的第一个元素。 Transformer 包中的所有模型都返回元组,因此是这个单成员元组。每个输入标记包含一个向量,包括特殊标记。

    3. 与 BERT 的 [CLS] 令牌是第一个令牌不同,这里的 <cls> 令牌是最后一个令牌(请参阅Transformers documentation)。如果你想比较分类向量,你应该从序列中取最后一个向量,即outputs[0][:, -1]

    或者,您可能想要比较嵌入的平均值(均值池)而不是 <cls> 令牌嵌入。在这种情况下,您可以使用output[0].mean(1)

    【讨论】:

    • 感谢您的回复。我尝试了您的建议,并且确实不再出现错误。但是,网络的性能真的很差。在计算句子的余弦相似度时:“我的兄弟会弹吉他。” “太阳普照。”我得到 0.93 的结果。我的代码如下所示: cos = nn.CosineSimilarity(dim=1, eps=1e-6) output = cos(last_hidden_​​states, last_hidden_​​states1) print(output)
    猜你喜欢
    • 2016-07-09
    • 2015-01-23
    • 1970-01-01
    • 2017-01-10
    • 2020-12-27
    • 2015-07-04
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    相关资源
    最近更新 更多