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

相似度loss汇总,pytorch code

用于约束图像生成,作为loss。

可梯度优化

  • pytorch structural similarity (SSIM) loss https://github.com/Po-Hsun-Su/pytorch-ssim
  • https://github.com/harveyslash/Facial-Similarity-with-Siamese-Networks-in-Pytorch/blob/master/Siamese-networks-medium.ipynb
class ContrastiveLoss(torch.nn.Module):"""Contrastive loss function.Based on: http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf"""def __init__(self, margin=2.0):super(ContrastiveLoss, self).__init__()self.margin = margindef forward(self, output1, output2, label):euclidean_distance = F.pairwise_distance(output1, output2, keepdim = True)loss_contrastive = torch.mean((1-label) * torch.pow(euclidean_distance, 2) +(label) * torch.pow(torch.clamp(self.margin - euclidean_distance, min=0.0), 2))return loss_contrastive
  • 多个集合,参看写法 Multi-Similarity Loss for Deep Metric Learning (MS-Loss)
  • 参考 https://blog.csdn.net/m0_46204224/article/details/117997854
@LOSS.register('ms_loss')
class MultiSimilarityLoss(nn.Module):def __init__(self, cfg):super(MultiSimilarityLoss, self).__init__()self.thresh = 0.5self.margin = 0.1self.scale_pos = cfg.LOSSES.MULTI_SIMILARITY_LOSS.SCALE_POSself.scale_neg = cfg.LOSSES.MULTI_SIMILARITY_LOSS.SCALE_NEGdef forward(self, feats, labels):assert feats.size(0) == labels.size(0), \f"feats.size(0): {feats.size(0)} is not equal to labels.size(0): {labels.size(0)}"batch_size = feats.size(0)sim_mat = torch.matmul(feats, torch.t(feats))epsilon = 1e-5loss = list()for i in range(batch_size):pos_pair_ = sim_mat[i][labels == labels[i]]pos_pair_ = pos_pair_[pos_pair_ < 1 - epsilon]neg_pair_ = sim_mat[i][labels != labels[i]]neg_pair = neg_pair_[neg_pair_ + self.margin > min(pos_pair_)]pos_pair = pos_pair_[pos_pair_ - self.margin < max(neg_pair_)]if len(neg_pair) < 1 or len(pos_pair) < 1:continue# weighting steppos_loss = 1.0 / self.scale_pos * torch.log(1 + torch.sum(torch.exp(-self.scale_pos * (pos_pair - self.thresh))))neg_loss = 1.0 / self.scale_neg * torch.log(1 + torch.sum(torch.exp(self.scale_neg * (neg_pair - self.thresh))))loss.append(pos_loss + neg_loss)if len(loss) == 0:return torch.zeros([], requires_grad=True)loss = sum(loss) / batch_sizereturn loss
  • Recall@k Surrogate Loss with Large Batches and Similarity Mixup https://github.com/yash0307/RecallatK_surrogate
class RecallatK(torch.nn.Module):def __init__(self, anneal, batch_size, num_id, feat_dims, k_vals, k_temperatures, mixup):super(RecallatK, self).__init__()assert(batch_size%num_id==0)self.anneal = annealself.batch_size = batch_sizeself.num_id = num_idself.feat_dims = feat_dimsself.k_vals = [min(batch_size, k) for k in k_vals]self.k_temperatures = k_temperaturesself.mixup = mixupself.samples_per_class = int(batch_size/num_id)def forward(self, preds, q_id):batch_size = preds.shape[0]num_id = self.num_idanneal = self.annealfeat_dims = self.feat_dimsk_vals = self.k_valsk_temperatures = self.k_temperaturessamples_per_class = int(batch_size/num_id)norm_vals = torch.Tensor([min(k, (samples_per_class-1)) for k in k_vals]).cuda()group_num = int(q_id/samples_per_class)q_id_ = group_num*samples_per_classsim_all = (preds[q_id]*preds).sum(1)sim_all_g = sim_all.view(num_id, int(batch_size/num_id))sim_diff_all = sim_all.unsqueeze(-1) - sim_all_g[group_num, :].unsqueeze(0).repeat(batch_size,1)sim_sg = sigmoid(sim_diff_all, temp=anneal)for i in range(samples_per_class): sim_sg[group_num*samples_per_class+i,i] = 0.sim_all_rk = (1.0 + torch.sum(sim_sg, dim=0)).unsqueeze(dim=0)sim_all_rk[:, q_id%samples_per_class] = 0.sim_all_rk = sim_all_rk.unsqueeze(dim=-1).repeat(1,1,len(k_vals))k_vals = torch.Tensor(k_vals).cuda()k_vals = k_vals.unsqueeze(dim=0).unsqueeze(dim=0).repeat(1, samples_per_class, 1)sim_all_rk = k_vals - sim_all_rkfor given_k in range(0, len(self.k_vals)):sim_all_rk[:,:,given_k] = sigmoid(sim_all_rk[:,:,given_k], temp=float(k_temperatures[given_k]))sim_all_rk[:,q_id%samples_per_class,:] = 0.k_vals_loss = torch.Tensor(self.k_vals).cuda()k_vals_loss = k_vals_loss.unsqueeze(dim=0)recall = torch.sum(sim_all_rk, dim=1)recall = torch.minimum(recall, k_vals_loss)recall = torch.sum(recall, dim=0)recall = torch.div(recall, norm_vals)recall = torch.sum(recall)/len(self.k_vals)return (1.-recall)/batch_size
  • Circle Loss https://github.com/TinyZeaMays/CircleLoss/blob/master/circle_loss.py

  • Torch的官方 https://pytorch.org/docs/1.12/nn.functional.html#loss-functions

  • KL散度

  • Hard Triplet loss

from __future__ import absolute_import
import sysimport torch
from torch import nn
DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")class TripletLoss(nn.Module):"""Triplet loss with hard positive/negative mining.Reference:Hermans et al. In Defense of the Triplet Loss for Person Re-Identification. arXiv:1703.07737.Code imported from https://github.com/Cysu/open-reid/blob/master/reid/loss/triplet.py.Args:margin (float): margin for triplet."""def __init__(self, margin=0.3):#三元组的阈值marginsuper(TripletLoss, self).__init__()self.margin = marginself.ranking_loss = nn.MarginRankingLoss(margin=margin)#三元组损失函数#ap an margin y:倍率   Relu(ap - anxy + margin)这个relu就起到和0比较的作用def forward(self, inputs, targets):"""Args:inputs: visualization_feature_map matrix with shape (batch_size, feat_dim)#32x2048targets: ground truth labels with shape (num_classes)#tensor([32])[1,1,1,1,2,3,2,,,,2]32个数,一个数代表ID的真实标签"""n = inputs.size(0)#取出输入的batch# Compute pairwise distance, replace by the official when merged#计算距离矩阵,其实就是计算两个2048维之间的距离平方(a-b)**2=a^2+b^2-2ab#[1,2,3]*[1,2,3]=[1,4,9].sum()=14  点乘dist = torch.pow(inputs, 2).sum(dim=1, keepdim=True).expand(n, n)dist = dist + dist.t()dist.addmm_(1, -2, inputs, inputs.t())#生成距离矩阵32x32,.t()表示转置dist = dist.clamp(min=1e-12).sqrt()  # for numerical stability#clamp(min=1e-12)加这个防止矩阵中有0,对梯度下降不好# For each anchor, find the hardest positive and negativemask = targets.expand(n, n).eq(targets.expand(n, n).t())#利用target标签的expand,并eq,获得mask的范围,由01组成,,红色1表示是同一个人,绿色0表示不是同一个人dist_ap, dist_an = [], []#用来存放ap,anfor i in range(n):#i表示行# dist[i][mask[i]],,i=0时,取mask的第一行,取距离矩阵的第一行,然后得到tensor([1.0000e-06, 1.0000e-06, 1.0000e-06, 1.0000e-06])dist_ap.append(dist[i][mask[i]].max().unsqueeze(0))#取某一行中,红色区域的最大值,mask前4个是1,与dist相乘dist_an.append(dist[i][mask[i] == 0].min().unsqueeze(0))#取某一行,绿色区域的最小值,加一个.unsqueeze(0)将其变成带有维度的tensordist_ap = torch.cat(dist_ap)dist_an = torch.cat(dist_an)# Compute ranking hinge lossy = torch.ones_like(dist_an)#y是个权重,长度像dist-anloss = self.ranking_loss(dist_an, dist_ap, y) #ID损失:交叉商输入的是32xf f.shape=分类数,然后loss用于计算损失#度量三元组:输入的是dist_an(从距离矩阵中,挑出一行(即一个ID)的最大距离),dist_ap#ranking_loss输入 an ap margin y:倍率  loss: Relu(ap - anxy + margin)这个relu就起到和0比较的作用# from IPython import embed# embed()return lossclass MultiSimilarityLoss(nn.Module):def __init__(self, margin=0.7):super(MultiSimilarityLoss, self).__init__()self.thresh = 0.5self.margin = marginself.scale_pos = 2.0self.scale_neg = 40.0def forward(self, feats, labels):assert feats.size(0) == labels.size(0), \f"feats.size(0): {feats.size(0)} is not equal to labels.size(0): {labels.size(0)}"batch_size = feats.size(0)feats = nn.functional.normalize(feats, p=2, dim=1)# Shape: batchsize * batch sizesim_mat = torch.matmul(feats, torch.t(feats))epsilon = 1e-5loss = list()mask = labels.expand(batch_size, batch_size).eq(labels.expand(batch_size, batch_size).t())for i in range(batch_size):pos_pair_ = sim_mat[i][mask[i]]pos_pair_ = pos_pair_[pos_pair_ < 1 - epsilon]neg_pair_ = sim_mat[i][mask[i] == 0]neg_pair = neg_pair_[neg_pair_ + self.margin > min(pos_pair_)]pos_pair = pos_pair_[pos_pair_ - self.margin < max(neg_pair_)]if len(neg_pair) < 1 or len(pos_pair) < 1:continue# weighting steppos_loss = 1.0 / self.scale_pos * torch.log(1 + torch.sum(torch.exp(-self.scale_pos * (pos_pair - self.thresh))))neg_loss = 1.0 / self.scale_neg * torch.log(1 + torch.sum(torch.exp(self.scale_neg * (neg_pair - self.thresh))))loss.append(pos_loss + neg_loss)# pos_loss =if len(loss) == 0:return torch.zeros([], requires_grad=True, device=feats.device)loss = sum(loss) / batch_sizereturn lossif __name__ == '__main__':#测试TripletLoss(nn.Module)use_gpu = Falsemodel = TripletLoss()features = torch.rand(32, 2048)label= torch.Tensor([1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5, 5, 5,  5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8,8]).long()loss = model(features, label)print(loss)

不可梯度优化

相关文章:

相似度loss汇总,pytorch code

用于约束图像生成&#xff0c;作为loss。 可梯度优化 pytorch structural similarity (SSIM) loss https://github.com/Po-Hsun-Su/pytorch-ssimhttps://github.com/harveyslash/Facial-Similarity-with-Siamese-Networks-in-Pytorch/blob/master/Siamese-networks-medium.ip…...

python中的yolov5结合PyQt5,使用QT designer设计界面没正确启动的解决方法

python中的yolov5结合PyQt5&#xff0c;使用QT designer设计界面没正确启动的解决方法 一、窗体设计test: 默认你已经设计好了窗体后&#xff1a; 这时你需要的是保存生成的untitle.ui到某个文件夹下&#xff0c;然后在命令行中奖.ui转换为.py&#xff08;&#xff0c;通过​​…...

Milk-V Duo移植rt-thread smart

前言 &#xff08;1&#xff09;PLCT实验室实习生长期招聘&#xff1a;招聘信息链接 &#xff08;2&#xff09;首先&#xff0c;我们拿到Milk-V Duo板子之后&#xff0c;我个人建议先移植大核Linux。因为那个资料相对多一点&#xff0c;也简单很多&#xff0c;现象也容易观察到…...

会声会影2024有哪些新功能?好不好用

比如会声会影视频编辑软件&#xff0c;既加入光影、动态特效的滤镜效果&#xff0c;也提供了与色彩调整相关的LUT配置文件滤镜&#xff0c;可选择性大&#xff0c;运用起来更显灵活。会声会影在用户的陪伴下走过20余载&#xff0c;经过上百个版本的优化迭代&#xff0c;已将操作…...

vue3 + axios 中断取消接口请求

前言 最近开发过程中&#xff0c;总是遇到想把正在请求的axios接口取消&#xff0c;这种情况有很多应用场景&#xff0c;举几个例子&#xff1a; 弹窗中接口请求返回图片&#xff0c;用于前端展示&#xff0c;接口还没返回数据&#xff0c;此时关闭弹窗&#xff0c;需要中断接…...

Linux高性能服务器编程——ch6笔记

第6章 高级I/O函数 6.1 pipe函数 用于创建一个管道&#xff0c;以实现进程间通信。 int pipe(int fd[2]); 读端文件描述符fd[0]和写端文件描述符fd[1]构成管道的两端&#xff0c;默认是阻塞的&#xff0c;fd[0]读出数据&#xff0c;fd[1]写入数据。管道内部传输的数据是字节…...

【C语言进阶】文件操作

文件操作 1. 为什么使用文件2. 什么是文件2.1程序文件2.2 数据文件2.3 文件名 3. 文件的打开和关闭3.1 文件指针3.2 文件的打开和关闭 4. 文件的顺序读写4.1 对比一组函数 5. 文件的随机读写5.1 fseek5.2 ftell5.3 rewind 6. 文本文件和二进制文件7. 文件读取结束的判定7.1 被错…...

Redis学习(第八章缓存策略)

目录 RdisExample 课程介绍 1.Redis介绍 2.Redis 安装 3. Redis的数据结构 4. Redis缓存特性 5. Redis使用场景 6. Redis客户端-Jedis 7. Jedis Pipeline 8. Redis缓存策略 学习资料 QA 相关问题 http, socket ,tcp的区别 RdisExample 项目代码地址&#xff1a;htt…...

springboot+vue开发的视频弹幕网站动漫网站

springbootvue开发的视频弹幕网站动漫网站 演示视频 https://www.bilibili.com/video/BV1MC4y137Qk/?share_sourcecopy_web&vd_source11344bb73ef9b33550b8202d07ae139b 功能&#xff1a; 前台&#xff1a; 首页&#xff08;猜你喜欢视频推荐&#xff09;、轮播图、分类…...

【CSS】常见 CSS 布局

1. 响应式布局 <!DOCTYPE html> <html><head><title>简单的响应式布局</title><style>/* 全局样式 */body {font-family: Arial, sans-serif;margin: 0;padding: 0;}/* 头部样式 */header {background-color: #333;color: #fff;padding: …...

数据结构---HashMap和HashSet

HashMap和HashSet都是存储在哈希桶之中&#xff0c;我们可以先了解一些哈希桶是什么。 像这样&#xff0c;一个数组数组的每个节点带着一个链表&#xff0c;数据就存放在链表结点当中。哈希桶插入/删除/查找节点的时间复杂度是O(1) map代表存入一个key值&#xff0c;一个val值…...

SLAM中相机姿态估计算法推导基础数学总结

相机模型 基本模型 内参 外参 对极几何 对极约束 外积符号 基础矩阵F和本质矩阵E 相机姿态估计问题分为如下两步: 本质矩阵 E t ∧ R Et^{\wedge}R Et∧R因为 t ∧ t^{\wedge} t∧其实就是个3x3的反对称矩阵&#xff0c;所以 E E E也是一个3x3的矩阵 用八点法估计E…...

【RS】遥感影像/图片64位、16位(64bit、16bit)的意义和区别

在数字图像处理中&#xff0c;我们常常会听到不同的位数术语&#xff0c;比如64位、16位和8位&#xff08;64bit、16bit、8bit&#xff09;。这些位数指的是图像的深度&#xff0c;也就是图像中每个像素可以显示的颜色数。位数越高&#xff0c;图像可以显示的颜色数就越多&…...

【单元测试】--基础知识

一、什么是单元测试 单元测试是软件开发中的一种测试方法&#xff0c;用于验证代码中的单个组件&#xff08;通常是函数、方法或类&#xff09;是否按预期工作。它旨在隔离和测试代码的最小单元&#xff0c;以确保其功能正确&#xff0c;提高代码质量和可维护性。单元测试通常…...

golang 反射机制

在 go 语言中&#xff0c;实现反射能力的是 reflect包&#xff0c;能够让程序操作不同类型的对象。其中&#xff0c;在反射包中有两个非常重要的 类型和 函数&#xff0c;两个函数分别是&#xff1a; reflect.TypeOfreflect.ValueOf 两个类型是 reflect.Type 和 reflect.Value…...

【Javascript】创建对象的几种方式

通过字面量创建对象 通过构造函数创建对象 Object()-------------构造函数 通过构造函数来实例化对象 给person注入属性 Factory工厂 this指向的是对象的本身使⽤new 实例化⼀个对象&#xff0c;就像⼯⼚⼀样...

深度学习_3_实战_房价预测

梯度 实战 代码&#xff1a; # %matplotlib inline import random import torch import matplotlib.pyplot as plt # from d21 import torch as d21def synthetic_data(w, b, num_examples):"""生成 Y XW b 噪声。"""X torch.normal(0,…...

HCIA -- 动态路由协议之RIP

一、静态协议的优缺点&#xff1a; 缺点&#xff1a; 1、中大型网络配置量过大 2、不能基于拓扑的变化而实时的变化 优点&#xff1a; 1、不会额外暂用物理资源 2、安全问题 3、计算路径问题 简单、小型网络建议使用静态路由&#xff1b;中大型较复杂网络&#xff0c;建议使用…...

JS常用时间操作moment.js参考文档

Moment.js是一个轻量级的JavaScript时间库&#xff0c;它方便了日常开发中对时间的操作&#xff0c;提高了开发效率。日常开发中&#xff0c;通常会对时间进行下面这几个操作&#xff1a;比如获取时间&#xff0c;设置时间&#xff0c;格式化时间&#xff0c;比较时间等等。下面…...

基于 FFmpeg 的跨平台视频播放器简明教程(九):Seek 策略

系列文章目录 基于 FFmpeg 的跨平台视频播放器简明教程&#xff08;一&#xff09;&#xff1a;FFMPEG Conan 环境集成基于 FFmpeg 的跨平台视频播放器简明教程&#xff08;二&#xff09;&#xff1a;基础知识和解封装&#xff08;demux&#xff09;基于 FFmpeg 的跨平台视频…...

反向工程与模型迁移:打造未来商品详情API的可持续创新体系

在电商行业蓬勃发展的当下&#xff0c;商品详情API作为连接电商平台与开发者、商家及用户的关键纽带&#xff0c;其重要性日益凸显。传统商品详情API主要聚焦于商品基本信息&#xff08;如名称、价格、库存等&#xff09;的获取与展示&#xff0c;已难以满足市场对个性化、智能…...

从深圳崛起的“机器之眼”:赴港乐动机器人的万亿赛道赶考路

进入2025年以来&#xff0c;尽管围绕人形机器人、具身智能等机器人赛道的质疑声不断&#xff0c;但全球市场热度依然高涨&#xff0c;入局者持续增加。 以国内市场为例&#xff0c;天眼查专业版数据显示&#xff0c;截至5月底&#xff0c;我国现存在业、存续状态的机器人相关企…...

关于iview组件中使用 table , 绑定序号分页后序号从1开始的解决方案

问题描述&#xff1a;iview使用table 中type: "index",分页之后 &#xff0c;索引还是从1开始&#xff0c;试过绑定后台返回数据的id, 这种方法可行&#xff0c;就是后台返回数据的每个页面id都不完全是按照从1开始的升序&#xff0c;因此百度了下&#xff0c;找到了…...

JVM垃圾回收机制全解析

Java虚拟机&#xff08;JVM&#xff09;中的垃圾收集器&#xff08;Garbage Collector&#xff0c;简称GC&#xff09;是用于自动管理内存的机制。它负责识别和清除不再被程序使用的对象&#xff0c;从而释放内存空间&#xff0c;避免内存泄漏和内存溢出等问题。垃圾收集器在Ja…...

ESP32 I2S音频总线学习笔记(四): INMP441采集音频并实时播放

简介 前面两期文章我们介绍了I2S的读取和写入&#xff0c;一个是通过INMP441麦克风模块采集音频&#xff0c;一个是通过PCM5102A模块播放音频&#xff0c;那如果我们将两者结合起来&#xff0c;将麦克风采集到的音频通过PCM5102A播放&#xff0c;是不是就可以做一个扩音器了呢…...

Rapidio门铃消息FIFO溢出机制

关于RapidIO门铃消息FIFO的溢出机制及其与中断抖动的关系&#xff0c;以下是深入解析&#xff1a; 门铃FIFO溢出的本质 在RapidIO系统中&#xff0c;门铃消息FIFO是硬件控制器内部的缓冲区&#xff0c;用于临时存储接收到的门铃消息&#xff08;Doorbell Message&#xff09;。…...

打手机检测算法AI智能分析网关V4守护公共/工业/医疗等多场景安全应用

一、方案背景​ 在现代生产与生活场景中&#xff0c;如工厂高危作业区、医院手术室、公共场景等&#xff0c;人员违规打手机的行为潜藏着巨大风险。传统依靠人工巡查的监管方式&#xff0c;存在效率低、覆盖面不足、判断主观性强等问题&#xff0c;难以满足对人员打手机行为精…...

android RelativeLayout布局

<?xml version"1.0" encoding"utf-8"?> <RelativeLayout xmlns:android"http://schemas.android.com/apk/res/android"android:layout_width"match_parent"android:layout_height"match_parent"android:gravity&…...

MySQL的pymysql操作

本章是MySQL的最后一章&#xff0c;MySQL到此完结&#xff0c;下一站Hadoop&#xff01;&#xff01;&#xff01; 这章很简单&#xff0c;完整代码在最后&#xff0c;详细讲解之前python课程里面也有&#xff0c;感兴趣的可以往前找一下 一、查询操作 我们需要打开pycharm …...

若依登录用户名和密码加密

/*** 获取公钥&#xff1a;前端用来密码加密* return*/GetMapping("/getPublicKey")public RSAUtil.RSAKeyPair getPublicKey() {return RSAUtil.rsaKeyPair();}新建RSAUti.Java package com.ruoyi.common.utils;import org.apache.commons.codec.binary.Base64; im…...