gpt4 book ai didi

python - 使用 T5 的句子嵌入

转载 作者:行者123 更新时间:2023-12-04 08:40:43 25 4
gpt4 key购买 nike

我想使用最先进的 LM T5 来获得句子嵌入向量。我找到了这个存储库 https://github.com/UKPLab/sentence-transformers据我所知,在 BERT 中我应该将第一个标记作为 [CLS] 标记,它将是句子嵌入。在此存储库中,我在 T5 模型上看到了相同的行为:

cls_tokens = output_tokens[:, 0, :]  # CLS token is first token

这种行为是否正确?我从 T5 中获取了编码器并用它编码了两个短语:

"I live in the kindergarden"
"Yes, I live in the kindergarden"

它们之间的余弦相似度仅为“0.2420”。

我只需要了解句子嵌入的工作原理——我是否应该训练网络来寻找相似性以获得正确的结果?或者我有足够的基础预训练语言模型?

最佳答案

为了从T5得到sentence embedding,需要从T5编码器的输出中获取last_hidden_​​state:

model.encoder(input_ids=s, attention_mask=attn, return_dict=True)
pooled_sentence = output.last_hidden_state # shape is [batch_size, seq_len, hidden_size]
# pooled_sentence will represent the embeddings for each word in the sentence
# you need to sum/average the pooled_sentence
pooled_sentence = torch.mean(pooled_sentence, dim=1)

你现在有一个来自 T5 的句子嵌入

关于python - 使用 T5 的句子嵌入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64579258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com