使用bert_base_chinese实现文本语义相似度计算

本文选择将模型下载到本地,进行离线分析计算,也可以使用在线下载,但本文略过

1 下载bert_base_chinese

下载地址:https://huggingface.co/google-bert/bert-base-chinese/tree/main

下载图上红框内的四个文件,并按照下图的目录结构放置

bert-base-chinese文件夹里放

2 代码

python 复制代码
import torch
from transformers import BertTokenizer, BertModel
from torch.nn.functional import cosine_similarity

# 初始化分词器和模型
vocab_file = 'D:/code/python/rpa/vocab.txt'
tokenizer = BertTokenizer.from_pretrained(vocab_file)
model = BertModel.from_pretrained('D:/code/python/rpa/bert-base-chinese')

def get_bert_embeddings(text):
    # 对文本进行分词
    inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512)
    # 获取BERT的输出
    with torch.no_grad():
        outputs = model(**inputs)
    # 获取最后一层的隐藏状态
    last_hidden_states = outputs.last_hidden_state
    # 取[CLS]标记的输出作为句子的表示
    sentence_embedding = last_hidden_states[:, 0, :]
    return sentence_embedding

# 计算两个文本的语义相似度
def calculate_similarity(text1, text2):
    emb1 = get_bert_embeddings(text1)
    emb2 = get_bert_embeddings(text2)
    
    # 计算余弦相似度
    # 将emb1和emb2调整为(batch_size, 1, embedding_dim),以便使用cosine_similarity
    similarity = cosine_similarity(emb1.unsqueeze(1), emb2.unsqueeze(1), dim=2)
    return similarity.item()

# 主函数
def main(text1, text2):
    similarity = calculate_similarity(text1, text2)
    print(f"The semantic similarity between the texts is: {similarity}")

text1 = '我的身体很健康'
text2 = '我没有生病'
main(text1, text2)
bash 复制代码
# result
The semantic similarity between the texts is: 0.8934338092803955
相关推荐
AI人工智能+1 分钟前
药品经营许可证识别技术,融合计算机视觉、自然语言处理和知识图谱,保障药品供应链安全,助力构建智慧药监体系。
深度学习·ocr·药品经营许可证识别
橙臣程9 分钟前
深度学习4——损失计算
人工智能
王同学的AI学习日记16 分钟前
Qwen-Image-3.0技术实测:文字渲染、长上下文与多场景能力深度评测
大数据·人工智能·ai·开源
wuhanzhanhui17 分钟前
质变的枢纽:2026 武汉国际储能产业博览会开启绿色能源的新周期
人工智能
后端小肥肠20 分钟前
Doubao-Seed-Evolving实测:我做了个情绪价值拉满的星座记账 Skill
人工智能·aigc·agent
Molesidy22 分钟前
【AI】【OpenCode】基于AI-Agent的工作方式的初步测试
人工智能
小码哥哥24 分钟前
私有化企业AI知识库技术架构:RAG系统全链路实现指南
人工智能·架构
小柯南敲键盘24 分钟前
Temu多语言商品图翻译实现方案
人工智能·python
问商十三载32 分钟前
2026法律行业AI引擎生成式优化怎么优化?三层专业加固提排名,零成本提33%引用率附适配表
java·前端·人工智能·算法
吨吨ai33 分钟前
2026年7月更新:ChatGPT、Codex、Pro、Plus 背后的 AI Observability(GPT-5.6 工程化技术分享)
人工智能·gpt·chatgpt