基于BERT的文本相似度计算

一、背景

  1. 最近在研究文本相似度,利用Bert去实现。
  2. 如果是在通用领域内进行文本相似度计算的话,就无需对Bert中文模型进行预训练,如果在特定领域内,就需要提前用大量的语料进行对google原版的中文模型进行预训练。
  3. bert用来提取句向量,然后利用余弦距离去计算相似度。

二、具体实现

  1. 利用苏神的bert4keras去构建网络模型,简单而又方便。
    贴一下苏神的bert4keras: https://github.com/bojone/bert4keras
from bert4keras.models import build_transformer_model
from bert4keras.tokenizers import Tokenizer
from sklearn.metrics.pairwise import euclidean_distances  # 欧氏距离
from sklearn.metrics.pairwise import cosine_similarity  # 余弦距离

config_path = '../model/finetune_model/bert_config.json'
checkpoint_path = r'../model/finetune_model_new/model.ckpt'
dict_path = '../model/finetune_model/vocab.txt'

def similar_count(vec1, vec2, model="cos"):
    '''
    计算距离
    :param vec1: 句向量1
    :param vec2: 句向量2
    :param model: 用欧氏距离还是余弦距离
    :return: 返回的是两个向量的距离得分
    '''
    if model == "eu":
        return euclidean_distances([vec1, vec2])[0][1]
    if model == "cos":
        return cosine_similarity([vec1, vec2])[0][1]

def main():
	# 根据配置文件,加载模型
	model = build_transformer_model(
	        config_path=config_path,
	        checkpoint_path=checkpoint_path,
	        with_pool=True,
	        return_keras_model=True,
	        model="bert"
	    )
	# 建立分词器
	tokenizer = Tokenizer(dict_path)
	
	# 要计算相似句子的标准句1
	stand_sent1 = "--------------------------------------------"
	# 要计算相似句子的标准句2
	stand_sent2 = "--------------------------------------------"
	
	# 得到两个句子的 token 和 segment
	token_ids1, segment_ids1 = tokenizer.encode(stand_sent1 , maxlen=128)
	token_ids2, segment_ids2 = tokenizer.encode(stand_sent2 , maxlen=128)
	
	# 通过模型得到两个句子的向量
	sentence_vec1 = model.predict([np.array([token_ids1]), np.array([segment_ids1])])[0]
	sentence_vec2 = model.predict([np.array([token_ids2]), np.array([segment_ids2])])[0]
	
	# 计算出得分
	score = similar_count(sentence_vec1, sentence_vec2)

	print(score)

if __name__ == '__main__':
    main()
  • 8
    点赞
  • 84
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值