当前位置: 首页 > news >正文

用 TripletLoss 优化bert ranking

下面是 用 TripletLoss 优化bert ranking 的demo


import torch
from torch.utils.data import DataLoader, Dataset
from transformers import BertModel, BertTokenizer
from sklearn.metrics.pairwise import pairwise_distancesclass TripletRankingDataset(Dataset):def __init__(self, queries, positive_docs, negative_docs, tokenizer, max_length):self.input_ids_q = []self.attention_masks_q = []self.input_ids_p = []self.attention_masks_p = []self.input_ids_n = []self.attention_masks_n = []for query, pos_doc, neg_doc in zip(queries, positive_docs, negative_docs):encoded_query = tokenizer.encode_plus(query, padding='max_length', truncation=True, max_length=max_length, return_tensors='pt')encoded_pos_doc = tokenizer.encode_plus(pos_doc, padding='max_length', truncation=True, max_length=max_length, return_tensors='pt')encoded_neg_doc = tokenizer.encode_plus(neg_doc, padding='max_length', truncation=True, max_length=max_length, return_tensors='pt')self.input_ids_q.append(encoded_query['input_ids'])self.attention_masks_q.append(encoded_query['attention_mask'])self.input_ids_p.append(encoded_pos_doc['input_ids'])self.attention_masks_p.append(encoded_pos_doc['attention_mask'])self.input_ids_n.append(encoded_neg_doc['input_ids'])self.attention_masks_n.append(encoded_neg_doc['attention_mask'])self.input_ids_q = torch.cat(self.input_ids_q, dim=0)self.attention_masks_q = torch.cat(self.attention_masks_q, dim=0)self.input_ids_p = torch.cat(self.input_ids_p, dim=0)self.attention_masks_p = torch.cat(self.attention_masks_p, dim=0)self.input_ids_n = torch.cat(self.input_ids_n, dim=0)self.attention_masks_n = torch.cat(self.attention_masks_n, dim=0)def __len__(self):return len(self.input_ids_q)def __getitem__(self, idx):input_ids_q = self.input_ids_q[idx]attention_mask_q = self.attention_masks_q[idx]input_ids_p = self.input_ids_p[idx]attention_mask_p = self.attention_masks_p[idx]input_ids_n = self.input_ids_n[idx]attention_mask_n = self.attention_masks_n[idx]return input_ids_q, attention_mask_q, input_ids_p, attention_mask_p, input_ids_n, attention_mask_nclass BERTTripletRankingModel(torch.nn.Module):def __init__(self, bert_model_name, hidden_size):super(BERTTripletRankingModel, self).__init__()self.bert = BertModel.from_pretrained(bert_model_name)self.dropout = torch.nn.Dropout(0.1)self.fc = torch.nn.Linear(hidden_size, 1)def forward(self, input_ids, attention_mask):outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask)pooled_output = self.dropout(outputs[1])logits = self.fc(pooled_output)return logits.squeeze()def triplet_loss(anchor, positive, negative, margin):distance_positive = torch.nn.functional.pairwise_distance(anchor, positive)distance_negative = torch.nn.functional.pairwise_distance(anchor, negative)losses = torch.relu(distance_positive - distance_negative + margin)return torch.mean(losses)# 初始化BERT模型和分词器
bert_model_name = 'bert-base-uncased'
tokenizer = BertTokenizer.from_pretrained(bert_model_name)# 示例输入数据
queries = ['I like cats', 'The sun is shining']
positive_docs = ['I like dogs', 'The weather is beautiful']
negative_docs = ['Snakes are dangerous', 'It is raining']# 超参数
batch_size = 8
max_length = 128
learning_rate = 1e-5
num_epochs = 5
margin = 1.0# 创建数据集和数据加载器
dataset = TripletRankingDataset(queries, positive_docs, negative_docs, tokenizer, max_length)
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)# 初始化模型并加载预训练权重
model = BERTTripletRankingModel(bert_model_name, hidden_size=model.bert.config.hidden_size)
optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)# 训练模型
model.train()for epoch in range(num_epochs):total_loss = 0for input_ids_q, attention_masks_q, input_ids_p, attention_masks_p, input_ids_n, attention_masks_n in dataloader:optimizer.zero_grad()embeddings_q = model(inputids_q, attention_masks_q)embeddings_p = model(input_ids_p, attention_masks_p)embeddings_n = model(input_ids_n, attention_masks_n)loss = triplet_loss(embeddings_q, embeddings_p, embeddings_n, margin)total_loss += loss.item()loss.backward()optimizer.step()print(f"Epoch {epoch+1}/{num_epochs} - Loss: {total_loss:.4f}")# 推断模型
model.eval()with torch.no_grad():embeddings = model.bert.embeddings.word_embeddings(dataset.input_ids_q)pairwise_distances = pairwise_distances(embeddings.numpy())# 输出结果
for i, query in enumerate(queries):print(f"Query: {query}")print("Documents:")for j, doc in enumerate(positive_docs):doc_idx = pairwise_distances[0][i * len(positive_docs) + j]doc_dist = pairwise_distances[1][i * len(positive_docs) + j]print(f"Document index: {doc_idx}, Distance: {doc_dist:.4f}")print(f"Document: {doc}")print("")print("---------")

相关文章:

用 TripletLoss 优化bert ranking

下面是 用 TripletLoss 优化bert ranking 的demo import torch from torch.utils.data import DataLoader, Dataset from transformers import BertModel, BertTokenizer from sklearn.metrics.pairwise import pairwise_distancesclass TripletRankingDataset(Dataset):def __…...

Tomcat安装及使用

这里写目录标题 Tomcat一.java基础1.java历史2.java组成3.实现动态网页功能serveltjsp 4.jdkJDK 和 JRE 关系安装openjdk安装oracle官方JDK 二.tomcat基础功能1.Tomcat介绍2.安装tomcat二进制安装Tomcat 3.配置文件介绍及核心组件配置文件组件 4.状态页5.常见的配置详解6.tomca…...

法国新法案强迫 Firefox 等浏览器审查网站

导读Mozilla 基金会已发起了一份请愿书,旨在阻止法国政府强迫 Mozilla Firefox 等浏览器审查网站。 据悉,法国政府正在制定一项旨在打击网络欺诈的 SREN 法案 (“Projet de loi Visant scuriser et reguler lespace numrique”),包含大约 2…...

开源电商项目 Mall:构建高效电商系统的终极选择

文章目录 Mall 项目概览前台商城系统后台管理系统系统架构图业务架构图 模块介绍后台管理系统 mall-admin商品管理:功能结构图-商品订单管理:功能结构图-订单促销管理:功能结构图-促销内容管理:功能结构图-内容用户管理&#xff1…...

QT(9.1)对话框与事件处理

作业: 1. 完善登录框 点击登录按钮后,判断账号(admin)和密码(123456)是否一致,如果匹配失败,则弹出错误对话框,文本内容“账号密码不匹配,是否重新登录”&…...

C++项目实战——基于多设计模式下的同步异步日志系统-③-前置知识补充-设计模式

文章目录 专栏导读六大原则单例模式饿汉模式懒汉模式 工厂模式简单工厂模式工厂方法模式抽象工厂模式 建造者模式代理模式 专栏导读 🌸作者简介:花想云 ,在读本科生一枚,C/C领域新星创作者,新星计划导师,阿…...

C++ 新旧版本两种读写锁

一、简介 读写锁(Read-Write Lock)是一种并发控制机制,用于多线程环境中实现对共享资源的高效读写操作。读写锁允许多个线程同时读取共享资源,但在有写操作时,需要互斥地独占对共享资源的访问,以确保数据的…...

ES6 字符串的repeat()方法

repeat() 方法返回一个新字符串,表示将原字符串重复n次 格式:str.repeat(n) 参数n:str需要重复多少次 参数n的取值: n是正整数: x.repeat(3) // 输出结果:"xxx" hello.repeat(2) // 输出结果…...

【车载以太网测试从入门到精通】系列文章目录汇总

【车载以太网测试从入门到精通】——物理层测试 【车载以太网测试从入门到精通】——数据链路层测试 【车载以太网测试从入门到精通】——网络层测试 【车载以太网测试从入门到精通】——传输层测试 【车载以太网测试从入门到精通】——以太网TCP/IP协议自动化测试(…...

LLM推理优化技术综述:KVCache、PageAttention、FlashAttention、MQA、GQA

LLM推理优化技术综述:KVCache、PageAttention、FlashAttention、MQA、GQA 随着大模型被越来越多的应用到不同的领域,随之而来的问题是应用过程中的推理优化问题,针对LLM推理性能优化有一些新的方向,最近一直在学习和研究&#xf…...

go开发之个微机器人的二次开发

请求URL: http://域名/addRoomMemberFriend 请求方式: POST 请求头Headers: Content-Type:application/jsonAuthorization:login接口返回 参数: 参数名必选类型说明wId是String登录实例标识chatRoom…...

2023国赛数学建模B题思路代码 - 多波束测线问题

# 1 赛题 B 题 多波束测线问题 单波束测深是利用声波在水中的传播特性来测量水体深度的技术。声波在均匀介质中作匀 速直线传播, 在不同界面上产生反射, 利用这一原理,从测量船换能器垂直向海底发射声波信 号,并记录从声波发射到…...

SpringAOP面向切面编程

文章目录 一. AOP是什么?二. AOP相关概念三. SpringAOP的简单演示四. SpringAOP实现原理 一. AOP是什么? AOP(Aspect Oriented Programming):面向切面编程,它是一种编程思想,是对某一类事情的集…...

A Guide to Java HashMap

原文链接: A Guide to Java HashMap → https://www.baeldung.com/java-hashmap 从Map里取值 # 原生方法 Map<String, Integer> map new HashMap<>();// map自身的方法 → 取不到返回null Integer age6 map.get("name"); // Integer时返回null可…...

LeetCode 449. Serialize and Deserialize BST【树,BFS,DFS,栈】困难

本文属于「征服LeetCode」系列文章之一&#xff0c;这一系列正式开始于2021/08/12。由于LeetCode上部分题目有锁&#xff0c;本系列将至少持续到刷完所有无锁题之日为止&#xff1b;由于LeetCode还在不断地创建新题&#xff0c;本系列的终止日期可能是永远。在这一系列刷题文章…...

嵌入式IDE(1):IAR中ICF链接文件详解和实例分析

最近在使用NXP的提供的MCUXPresso IDE&#xff0c;除了Eclipse固有的优点外&#xff0c;我觉得它最大的优点就是在链接脚本的生成上&#xff0c;提供了非常直观的GUI配置界面。但这个IDE仅仅支持NXP相关的产品&#xff0c;而且调试的性能在某些情况下并不理想。而我们用得比较多…...

分布式版本控制工具——git

✅<1>主页&#xff1a;&#xff1a;我的代码爱吃辣 &#x1f4c3;<2>知识讲解&#xff1a;Linux——git ☂️<3>开发环境&#xff1a;Centos7 &#x1f4ac;<4>前言&#xff1a;git是一个开源的分布式版本控制系统&#xff0c;可以有效、高速地处理从很…...

C基础-数组

1.一维数组的创建和初始化 int main() {// int arr1[10];int n 0;scanf("%d",&n);//int count 10;int arr2[n]; //局部的变量&#xff0c;这些局部的变量或者数组是存放在栈区的&#xff0c;存放在栈区上的数组&#xff0c;如果不初始化的话&#xff0c;默认…...

springboot项目配置flyway菜鸟级别教程

1、Flyway的工作原理 Flyway在第一次执行时&#xff0c;会创建一个默认名为flyway_schema_history的历史记录表&#xff0c;这张表会用来跟踪或记录数据库的状态&#xff0c;然后每次项目启动时都会自动扫描在resources/db/migration下的文件的版本号并且通过查询flyway_schem…...

成都精灵云初试

最近参加了成都精灵云的笔试与面试&#xff0c;岗位是c工程师。后面自己复盘了过程&#xff0c;初试部分总结如下&#xff0c;希望能对各位相进该公司以及面试C工程师的同学提供一些参考。这也是博主第一次参加面试&#xff0c;很多东西都还没准备&#xff0c;很多答得不好&…...

利用最小二乘法找圆心和半径

#include <iostream> #include <vector> #include <cmath> #include <Eigen/Dense> // 需安装Eigen库用于矩阵运算 // 定义点结构 struct Point { double x, y; Point(double x_, double y_) : x(x_), y(y_) {} }; // 最小二乘法求圆心和半径 …...

Python:操作 Excel 折叠

💖亲爱的技术爱好者们,热烈欢迎来到 Kant2048 的博客!我是 Thomas Kant,很开心能在CSDN上与你们相遇~💖 本博客的精华专栏: 【自动化测试】 【测试经验】 【人工智能】 【Python】 Python 操作 Excel 系列 读取单元格数据按行写入设置行高和列宽自动调整行高和列宽水平…...

ssc377d修改flash分区大小

1、flash的分区默认分配16M、 / # df -h Filesystem Size Used Available Use% Mounted on /dev/root 1.9M 1.9M 0 100% / /dev/mtdblock4 3.0M...

Java 二维码

Java 二维码 **技术&#xff1a;**谷歌 ZXing 实现 首先添加依赖 <!-- 二维码依赖 --><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.5.1</version></dependency><de…...

Vite中定义@软链接

在webpack中可以直接通过符号表示src路径&#xff0c;但是vite中默认不可以。 如何实现&#xff1a; vite中提供了resolve.alias&#xff1a;通过别名在指向一个具体的路径 在vite.config.js中 import { join } from pathexport default defineConfig({plugins: [vue()],//…...

LangFlow技术架构分析

&#x1f527; LangFlow 的可视化技术栈 前端节点编辑器 底层框架&#xff1a;基于 &#xff08;一个现代化的 React 节点绘图库&#xff09; 功能&#xff1a; 拖拽式构建 LangGraph 状态机 实时连线定义节点依赖关系 可视化调试循环和分支逻辑 与 LangGraph 的深…...

Linux中《基础IO》详细介绍

目录 理解"文件"狭义理解广义理解文件操作的归类认知系统角度文件类别 回顾C文件接口打开文件写文件读文件稍作修改&#xff0c;实现简单cat命令 输出信息到显示器&#xff0c;你有哪些方法stdin & stdout & stderr打开文件的方式 系统⽂件I/O⼀种传递标志位…...

【UE5 C++】通过文件对话框获取选择文件的路径

目录 效果 步骤 源码 效果 步骤 1. 在“xxx.Build.cs”中添加需要使用的模块 &#xff0c;这里主要使用“DesktopPlatform”模块 2. 添加后闭UE编辑器&#xff0c;右键点击 .uproject 文件&#xff0c;选择 "Generate Visual Studio project files"&#xff0c;重…...

面试高频问题

文章目录 &#x1f680; 消息队列核心技术揭秘&#xff1a;从入门到秒杀面试官1️⃣ Kafka为何能"吞云吐雾"&#xff1f;性能背后的秘密1.1 顺序写入与零拷贝&#xff1a;性能的双引擎1.2 分区并行&#xff1a;数据的"八车道高速公路"1.3 页缓存与批量处理…...

Django RBAC项目后端实战 - 03 DRF权限控制实现

项目背景 在上一篇文章中&#xff0c;我们完成了JWT认证系统的集成。本篇文章将实现基于Redis的RBAC权限控制系统&#xff0c;为系统提供细粒度的权限控制。 开发目标 实现基于Redis的权限缓存机制开发DRF权限控制类实现权限管理API配置权限白名单 前置配置 在开始开发权限…...