使用 T5 的句子嵌入

Sentence embedding using T5

我想使用最先进的 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 的句子嵌入