本地运行《使用AMD上的SentenceTransformers构建语义搜索》

news2024/10/6 4:03:10

Building semantic search with SentenceTransformers on AMD — ROCm Blogs

这篇博客解释了如何在Sentence Compression数据集上训练SentenceTransformers模型来执行语义搜索。使用BERT基础模型(不区分大小写)作为基础的变换器,并应用Hugging Face的PyTorch库。
训练这个自定义模型的目标是将其用于执行语义搜索。语义搜索是一种信息检索方法,它理解搜索查询的意图和上下文,而不仅仅是匹配关键词。例如,搜索“苹果派食谱”(查询)将返回关于如何制作苹果派的结果(文档),而不仅仅是包含“苹果”和“派”这些词的页面。
可以在这个[GitHub文件夹](https://github.com/ROCm/rocm-blogs/tree/release/blogs/artificial-intelligence/sentence_transformers_amd/)中找到与这篇博客文章相关的文件。

介绍SentenceTransformers

从头开始训练一个SentenceTransformers模型包括一个过程,即教导模型理解和编码句子为有意义的、高维度的向量。在这篇博客中,专注于一个包含等价句子对的数据集。总的来说,培训过程的目标是让模型学习如何将语义上相似的句子映射在向量空间中的接近位置,同时将不相似的句子分隔开。与可能无法捕获某些领域或用例的特定性质的通用预训练模型相比,自定义训练模型确保模型能够精确调整以理解与特定领域或应用相关的上下文和语义。
感兴趣的是执行非对称语义搜索。在这种方法中,模型承认查询和文档本质上可以是不同的。例如,具有简短查询和长文档。非对称语义搜索使用编码,使搜索更加有效,即使在文本类型或长度不匹配时也是如此。这对于信息从大型文档或数据库检索的应用非常有用,其中查询通常比他们搜索的内容更短且不那么详细。这里有一个语义搜索如何工作的例子:

查询:巴黎位于法国吗?
语料库中最相似的句子:
法国的首都是巴黎(得分:0.6829)
巴黎是欧洲的一个城市,有着传统和杰出的食物,是法国的首都(得分:0.6044)
澳大利亚以其传统和杰出的食物而闻名(得分:-0.0159)

基于AMD GPU的实现

案例在Ubuntu 22.04.3 LTS系统ROCm 6.0.2和PyTorch 2.3.0版本进行。

$ python
Python 3.12.1 | packaged by Anaconda, Inc. | (main, Jan 19 2024, 15:51:05) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.__version__
'2.3.0+rocm6.0'

安装以下Python包:

pip install datasets ipywidgets -U transformers sentence-transformers

从HF-Mirror - Huggingface 镜像站下载Sentence Compression 数据集:

./hfd.sh embedding-data/sentence-compression --dataset --tool aria2c -x 4

句子压缩(Sentence Compression)数据集包含18万对等价句子。这些句子对演示了如何把较长的句子压缩成较短的句子,同时保持相同的含义。

导入Python包

from datasets import load_dataset  # 从datasets库中导入load_dataset方法  
from sentence_transformers import InputExample, util  # 从sentence_transformers库中导入InputExample和util模块  
from torch.utils.data import DataLoader  # 从torch库中导入DataLoader类  
from torch import nn  # 从torch库中导入神经网络相关模块  
from sentence_transformers import losses  # 从sentence_transformers库中导入losses模块  
from sentence_transformers import SentenceTransformer, models  # 从sentence_transformers库中导入SentenceTransformer和models模块

准备数据集:

dataset_id = "./sentence-compression"
dataset = load_dataset(dataset_id)

查看数据集中的一个样本:

# 查看一个样本
print(dataset['train']['set'][1])
['Major League Baseball Commissioner Bud Selig will be speaking at St. Norbert College next month.',
'Bud Selig to speak at St. Norbert College']

SentenceTransformers库要求数据集需要有特定的格式,确保数据与模型架构兼容。

创建训练样本的列表(使用数据集的一半来进行说明)。这种方法减少了计算负载并加速了训练过程。

# 转换数据集为所需格式
train_examples = []
train_data = dataset['train']['set']

n_examples = dataset['train'].num_rows // 2  # 选择一半的数据集进行训练

for example in train_data[:n_examples]:
    original_sentence = example[0]
    compressed_sentence = example[1]

    input_example = InputExample(texts=[original_sentence, compressed_sentence])

    train_examples.append(input_example)

实例化`DataLoader`类。这个类为提供了一个有效地迭代数据集的方式。

# 使用训练样本实例化DataLoader
train_dataloader = DataLoader(train_examples, shuffle=True, batch_size=16)

实现

在句子转换器模型中,目的是将不定长的输入句子映射为一个固定大小的向量。首先,将输入句子传递给一个转换模型。在这个例子中,使用了BERT基础模型(不区分大小写版本)作为基础转换模型,它会输出输入句子中每个词的上下文化嵌入向量。获取到每个词的嵌入向量后,使用汇聚层(Pooling layer)来将这些向量整合为一个单独的句子嵌入向量。最后,通过添加一个全连接层(具有双曲正切激活函数的dense层)进行额外的变换。这个层的作用是降低汇聚后的句子嵌入向量的维度,同时使用非线性激活函数让模型能够捕捉数据中更复杂的模式。

# 创建一个自定义模型
# 使用一个已存在的嵌入模型
word_embedding_model = models.Transformer('bert-base-uncased', max_seq_length=256)

# 对token嵌入向量使用汇聚函数
pooling_model = models.Pooling(word_embedding_model.get_word_embedding_dimension())

# 全连接层
dense_model = models.Dense(in_features=pooling_model.get_sentence_embedding_dimension(), out_features=256, activation_function=nn.Tanh())

# 定义整体模型
model = SentenceTransformer(modules=[word_embedding_model, pooling_model, dense_model])

训练

在训练过程中,选择合适的损失函数是至关重要的,这取决于具体应用和数据集的结构。在这里,使用了`MultipleNegativesRankingLoss`函数。这个函数在句子的语义搜索应用中特别有用,因为模型需要根据句子的相关性对其进行排序。它的工作方式是将一对语义相似的句子(正例对)与多个语义不相似的句子进行对比。这个函数非常适合句子压缩数据集,因为它能够区分语义相似和不相似的句子。

# 鉴于有等效句子对的数据集,选择MultipleNegativesRankingLoss
train_loss = losses.MultipleNegativesRankingLoss(model = model)
model.fit(train_objectives=[(train_dataloader, train_loss)], epochs = 5)

推理

评估这个模型。

# 从 sentence_transformers 导入 SentenceTransformer 和 util
import torch

# 待编码的句子们(文档/语料库)
sentences = [
    'Paris, which is a city in Europe with traditions and remarkable food, is the capital of France',
    'The capital of France is Paris',
    'Australia is known for its traditions and remarkable food',
    """
        Despite the heavy rains that lasted for most of the week, the outdoor music festival,
        which featured several renowned international artists, was able to proceed as scheduled,
        much to the delight of fans who had traveled from all over the country
    """,
    """
        Photosynthesis, a process used by plans and other organisms to convert light into
        chemical energy, plays a crucial role in maintaining the balance of oxygen and carbon
        dioxide in the Earth's atmosphere.
    """
]

# 编码句子
sentences_embeddings = model.encode(sentences, convert_to_tensor=True)


# 查询句子:
queries = ['Is Paris located in France?', 'Tell me something about Australia',
           'music festival proceeding despite heavy rains',
           'what is the process that some organisms use to transform light into chemical energy?']


# 使用余弦相似度为每个查询寻找语料库中最接近的句子
for query in queries:

    # 编码当前查询
    query_embedding = model.encode(query, convert_to_tensor=True)

    # 余弦相似度及查询最接近的文档
    cos_scores = util.cos_sim(query_embedding, sentences_embeddings)[0] # 计算相似度得分

    top_results = torch.argsort(cos_scores, descending = True) # 得分降序排列
    print("\n\n======================\n\n")
    print("Query:", query)
    print("\nSimilar sentences in corpus:") # 输出语料库中相似的句子

    # 遍历输出与查询最相似的句子及其得分
    for idx in top_results:
        print(sentences[idx], "(Score: {:.4f})".format(cos_scores[idx]))

通过使用几个新示例来测试模型,从而展示其有效性。

======================


Query: Is Paris located in France?

Similar sentences in corpus:
The capital of France is Paris (Score: 0.7907)
Paris, which is a city in Europe with traditions and remarkable food, is the capital of France (Score: 0.7081)

        Photosynthesis, a process used by plans and other organisms to convert light into
        chemical energy, plays a crucial role in maintaining the balance of oxygen and carbon
        dioxide in the Earth's atmosphere.
     (Score: 0.0657)
Australia is known for its traditions and remarkable food (Score: 0.0162)

        Despite the heavy rains that lasted for most of the week, the outdoor music festival,
        which featured several renowned international artists, was able to proceed as scheduled,
        much to the delight of fans who had traveled from all over the country
     (Score: -0.0934)


======================


Query: Tell me something about Australia

Similar sentences in corpus:
Australia is known for its traditions and remarkable food (Score: 0.6730)
Paris, which is a city in Europe with traditions and remarkable food, is the capital of France (Score: 0.1489)
The capital of France is Paris (Score: 0.1146)

        Despite the heavy rains that lasted for most of the week, the outdoor music festival, 
        which featured several renowned international artists, was able to proceed as scheduled, 
        much to the delight of fans who had traveled from all over the country
     (Score: 0.0694)

        Photosynthesis, a process used by plans and other organisms to convert light into
        chemical energy, plays a crucial role in maintaining the balance of oxygen and carbon
        dioxide in the Earth's atmosphere.
     (Score: -0.0241)


======================


Query: music festival proceeding despite heavy rains

Similar sentences in corpus:

        Despite the heavy rains that lasted for most of the week, the outdoor music festival,
        which featured several renowned international artists, was able to proceed as scheduled,
        much to the delight of fans who had traveled from all over the country
     (Score: 0.7855)
Paris, which is a city in Europe with traditions and remarkable food, is the capital of France (Score: 0.0700)

        Photosynthesis, a process used by plans and other organisms to convert light into
        chemical energy, plays a crucial role in maintaining the balance of oxygen and carbon
        dioxide in the Earth's atmosphere.
     (Score: 0.0351)
The capital of France is Paris (Score: 0.0037)
Australia is known for its traditions and remarkable food (Score: -0.0552)


======================


Query: what is the process that some organisms use to transform light into chemical energy?

Similar sentences in corpus:

        Photosynthesis, a process used by plans and other organisms to convert light into
        chemical energy, plays a crucial role in maintaining the balance of oxygen and carbon
        dioxide in the Earth's atmosphere.
     (Score: 0.6085)

        Despite the heavy rains that lasted for most of the week, the outdoor music festival,
        which featured several renowned international artists, was able to proceed as scheduled,
        much to the delight of fans who had traveled from all over the country
     (Score: 0.1370)
Paris, which is a city in Europe with traditions and remarkable food, is the capital of France (Score: 0.0141)
Australia is known for its traditions and remarkable food (Score: 0.0102)
The capital of France is Paris (Score: -0.0128)

完整代码

from datasets import load_dataset
from sentence_transformers import InputExample, util
from torch.utils.data import DataLoader
from torch import nn
from sentence_transformers import losses
from sentence_transformers import SentenceTransformer, models

dataset_id = "./sentence-compression"
dataset = load_dataset(dataset_id)

# 探索一个样本
print(dataset['train']['set'][1])

#将数据集转换为所需格式
train_examples = [] # 创建训练样本列表
train_data = dataset['train']['set'] # 获取训练数据集

n_examples = dataset['train'].num_rows//2 # 选择数据集的一半进行训练

# 遍历选定的样本并创建输入示例
for example in train_data[:n_examples]:
    original_sentence = example[0] # 原始句子
    compressed_sentence = example[1] # 压缩后的句子

    input_example = InputExample(texts = [original_sentence, compressed_sentence]) # 创建输入示例

    train_examples.append(input_example) # 将输入示例添加到列表中

# 使用训练示例实例化数据加载器
train_dataloader = DataLoader(train_examples, shuffle = True, batch_size = 16) # 初始化数据加载器


# 创建自定义模型
# 使用现有的嵌入模型
word_embedding_model = models.Transformer('bert-base-uncased', max_seq_length=256) # 初始化词嵌入模型

# 对令牌嵌入应用池化函数
pooling_model = models.Pooling(word_embedding_model.get_word_embedding_dimension()) # 初始化池化模型

# 密集函数
dense_model = models.Dense(in_features=pooling_model.get_sentence_embedding_dimension(), out_features=256, activation_function=nn.Tanh()) # 初始化密集层模型

# 定义整体模型
model = SentenceTransformer(modules=[word_embedding_model, pooling_model, dense_model]) # 组装模型各层组件

# 给定等效句子数据集,选择MultipleNegativesRankingLoss作为训练损失
train_loss = losses.MultipleNegativesRankingLoss(model = model) # 初始化训练损失
model.fit(train_objectives=[(train_dataloader, train_loss)], epochs = 5) # 训练模型

# from sentence_transformers import SentenceTransformer, util
import torch

# 待编码的句子们(文档/语料库)
sentences = [
    'Paris, which is a city in Europe with traditions and remarkable food, is the capital of France',
    'The capital of France is Paris',
    'Australia is known for its traditions and remarkable food',
    """
        Despite the heavy rains that lasted for most of the week, the outdoor music festival,
        which featured several renowned international artists, was able to proceed as scheduled,
        much to the delight of fans who had traveled from all over the country
    """,
    """
        Photosynthesis, a process used by plans and other organisms to convert light into
        chemical energy, plays a crucial role in maintaining the balance of oxygen and carbon
        dioxide in the Earth's atmosphere.
    """
]

# 编码句子
sentences_embeddings = model.encode(sentences, convert_to_tensor=True)


# 查询句子:
queries = ['Is Paris located in France?', 'Tell me something about Australia',
           'music festival proceeding despite heavy rains',
           'what is the process that some organisms use to transform light into chemical energy?']


# 使用余弦相似度为每个查询寻找语料库中最接近的句子
for query in queries:

    # 编码当前查询
    query_embedding = model.encode(query, convert_to_tensor=True)

    # 余弦相似度及查询最接近的文档
    cos_scores = util.cos_sim(query_embedding, sentences_embeddings)[0] # 计算相似度得分

    top_results = torch.argsort(cos_scores, descending = True) # 得分降序排列
    print("\n\n======================\n\n")
    print("Query:", query)
    print("\nSimilar sentences in corpus:") # 输出语料库中相似的句子

    # 遍历输出与查询最相似的句子及其得分
    for idx in top_results:
        print(sentences[idx], "(Score: {:.4f})".format(cos_scores[idx]))

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1673062.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

家居分类的添加、修改、逻辑删除和批量删除

文章目录 1.逻辑删除家居分类1.将之前的docker数据库换成云数据库2.树形控件增加添加和删除按钮1.找到控件2.粘贴四个属性到<el-tree 属性>3.粘贴两个span到<el-tree>标签里4.代码5.效果6.方法区新增两个方法处理添加和删除分类7.输出查看一下信息8.要求节点等级小…

Spring AI项目Open AI绘画开发指导

Spring AI项目创建 Spring AI简介创建Spring AI项目配置项目pom和application文件controller接口开发运行测试 Spring AI简介 Spring AI 是 AI 工程的应用框架。其目标是将 Spring 生态系统设计原则&#xff08;如可移植性和模块化设计&#xff09;应用于 AI&#xff0c;并推广…

自作聪明的AI? —— 信息处理和传递误区

一、背景 在人与人的信息传递中有一个重要问题——由于传递人主观处理不当&#xff0c;导致信息失真或产生误导。在沟通交流中&#xff0c;确实存在“自作聪明”的现象&#xff0c;即传递人在转述或解释信息时&#xff0c;根据自己对信息的理解、经验以及个人意图进行了过多的…

SpringSecurity6实现动态权限,rememberMe、OAuth2.0授权登录,退出登录等功能

本文章对应视频可在B站查看SpringSecurity6对应视频教程&#xff0c;记得三连哦&#xff0c;这对我很重要呢&#xff01; 温馨提示&#xff1a;视频与文章相辅相成&#xff0c;结合学习效果更强哦&#xff01; 系列文章链接 1、初识SpringSecurity&#xff0c;认识主流Java权限…

AI+文旅|当智慧遇见风景,感受文旅新体验

今年的五一假期,公众出游热度持续升温&#xff0c;全国多地景区再现“人山人海”&#xff0c;在这样的背景下&#xff0c;促使文旅行业不断通过数字化手段&#xff0c;提升旅游体验质量、探索新的服务方式&#xff0c;AI技术的加入为旅游业带来了革命性的变化。智能导游、智能推…

FOTS:一种用于机器人操作技能Sim2Real学习的快速光学触觉仿真器

类 GelSight的视触觉传感器具有高分辨率和低制造成本的优势&#xff0c;但是在与现实中的物体进行频繁接触时易受磨损。而触觉仿真器可大幅降低硬件成本&#xff0c;同时为后续技能学习任务提供仿真训练环境。为此&#xff0c;来自东南大学自动化学院的钱堃副教授研究团队和伦敦…

大厂常见算法50题-两数相加

专栏持续更新50道算法题&#xff0c;都是大厂高频算法题&#xff0c;建议关注, 一起巧‘背’算法! 文章目录 题目解法总结 题目 解法 定义一个节点pre&#xff0c;用于初始化结果链表的头部&#xff0c;cur指向pre&#xff0c;它将在遍历过程中用于构建新的链表。初始化进位变…

基于单片机的直流电机测速装置研究与设计

摘要: 基于单片机的直流电机测速装置采用了对直流电机的中枢供电回路串联取样电阻的方式实现对电机转速的精确实时测量。系统由滤波电路、信号放大电路、单片机控制电路以及稳压电源等功能模块电路构成。工作过程中高频磁环作为载体&#xff0c;利用电磁感应的基本原理对直流电…

使用Flask部署Web应用:从入门到精通

文章目录 第一部分&#xff1a;准备工作第二部分&#xff1a;部署Flask应用到AWS部署到AWS Lambda 第三部分&#xff1a;部署Flask应用到腾讯云服务器部署到腾讯云服务器 第四部分&#xff1a;优化和扩展结论 在现代软件开发中&#xff0c;Web应用的部署是一个至关重要的环节。…

面试题:调整数字顺序,使奇数位于偶数前面

题目&#xff1a; 输入一个整数数组&#xff0c;实现一个函数&#xff0c;来调整该数组中数字的顺序 使得所有奇数位于数组的前半部分&#xff0c;所有偶数位于数组的后半部分 算法1&#xff1a; 利用快速排序的一次划分思想&#xff0c;从2端往中间遍历 时间复杂度&#x…

【漏洞复现】泛微OA E-Cology ResourceServlet文件读取漏洞

漏洞描述&#xff1a; 泛微OA E-Cology是一款面向中大型组织的数字化办公产品&#xff0c;它基于全新的设计理念和管理思想&#xff0c;旨在为中大型组织创建一个全新的高效协同办公环境。泛微OA E-Cology ResourceServlet存在任意文件读取漏洞&#xff0c;允许未经授权的用户…

网络安全之OSPF进阶

该文针对OSPF进行一个全面的认识。建议了解OSPF的基础后进行本文的一个阅读能较好理解本文。 OSPF基础的内容请查看&#xff1a;网络安全之动态路由OSPF基础-CSDN博客 OSPF中更新方式中的触发更新30分钟的链路状态刷新。是因为其算法决定的&#xff0c;距离矢量型协议是边算边…

【java-数据结构14-双向链表的增删查改2】

上一篇文章中&#xff0c;我们已经对双向链表进行一些基本操作&#xff0c;本篇文章我们继续通过对链表的增删查改来加深对链表的理解~同时有任何不懂的地方可以在评论区留言讨论&#xff0c;也可以私信小编~觉得小编写的还可以的可以留个关注支持一下~话不多说正片开始~ 注意…

「JavaEE」多线程案例分析3:线程池

&#x1f387;个人主页&#xff1a;Ice_Sugar_7 &#x1f387;所属专栏&#xff1a;JavaEE &#x1f387;欢迎点赞收藏加关注哦&#xff01; 线程池 &#x1f349;简介&#x1f349;标准库中的线程池&#x1f349;Executors&#x1f349;实现一个简单的线程池 &#x1f349;简介…

初始Django

初始Django 一、Django的历史 ​ Django 是从真实世界的应用中成长起来的&#xff0c;它是由堪萨斯&#xff08;Kansas&#xff09;州 Lawrence 城中的一个网络开发小组编写的。它诞生于 2003 年秋天&#xff0c;那时 Lawrence Journal-World 报纸的程序员 Adrian Holovaty 和…

识别AI论文生成内容,降低论文高AI率

AI写作工具能帮我们在短时间内高效生成一篇毕业论文、开通报告、文献综述、任务书、调研报告、期刊论文、课程论文等等&#xff0c;导致许多人开始使用AI写作工具作为撰写学术论文的辅助手段。而学术界为了杜绝此行为&#xff0c;开始使用AIGC检测系统来判断文章是由AI生成还是…

机器学习中的聚类

目录 认识聚类算法 聚类算法API的使用 聚类算法实现流程 聚类算法模型评估 认识聚类算法 聚类算法是一种无监督的机器学习算法。 它将一组数据分成若干个不同的群组&#xff0c;使得每个群组内部的数据点相似度高&#xff0c;而不同群组之间的数据点相似度低。常用的相似…

【3dmax笔记】028:倒角的使用方法

一、倒角描述 在3dmax中创建倒角效果可以通过多种方法实现,以下是几种常见的方法: 使用倒角修改器。首先创建一个图形(如矩形和圆),然后对齐它们,将它们转化为可编辑样条线,并附加在一起,选择要倒角的边缘,然后使用倒角修改器来调整高度、轮廓等参数。使用倒角剖面修…

Davinci工程vBaseEnv模块讲解

配合的模块 要正常使用vBaseEnv模块&#xff0c;要同时使能EcuC、OS、vBRS和vLinkGen模块。 OS是操作系统&#xff0c;除了FBL以外&#xff0c;其他都需要用到OS。 vBaseEnv是基础环境 vBRS是基本运行系统 vLinkGen脚本链接生成器 EcuC是ECU配置 EcuC配置 需要配合vBaseEnv模…

程序员的神奇应用:从代码创造到问题解决的魔法世界之持续集成/持续部署

文章目录 持续集成/持续部署 在软件开发的海洋中&#xff0c;程序员的实用神器如同航海中的指南针&#xff0c;帮助他们导航、加速开发、优化代码质量&#xff0c;并最终抵达成功的彼岸。这些工具覆盖了从代码编写、版本控制到测试和部署的各个环节。 在当今数字化的世界里&…