BERT(Bidirectional Encoder Representations from Transformers)是一种基于Transformer架构的预训练语言模型,它能够捕捉到文本的双向上下文信息,非常适合用于各种自然语言处理任务,包括句子语义相似度的预测。
以下是一个使用Python和Transformers库来预测句子语义相似度的示例:
from transformers import BertTokenizer, BertModel
import torch
from scipy.spatial.distance import cosine
# 加载预训练的BERT模型和分词器
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertModel.from_pretrained('bert-base-uncased')
# 定义两个句子
sentence1 = "The cat sat on the mat."
sentence2 = "A feline is perched on a rug."
# 对句子进行编码
inputs = tokenizer(sentence1, sentence2, return_tensors='pt', truncation=True, padding=True)
# 获取BERT的输出
with torch.no_grad():
outputs = model(**inputs)
# 获取句子嵌入(取[CLS]标记的输出作为句子的向量表示)
sentence_embedding1 = outputs.last_hidden_state[:, 0, :]
sentence_embedding2 = outputs.last_hidden_state[:, 1, :]
# 计算余弦相似度
similarity = 1 - cosine(sentence_embedding1, sentence_embedding2)
print(f"The semantic similarity between the sentences is: {similarity.item()}")
通过以上步骤和方法,你可以有效地使用BERT模型来预测无标签数据集中句子的语义相似度。
领取专属 10元无门槛券
手把手带您无忧上云