直接写法

import numpy as npdef bit_product_sum(x, y):return sum([item[0] * item[1] for item in zip(x, y)])def cosine_similarity(x, y, norm=False):""" 计算两个向量x和y的余弦相似度 """assert len(x) == len(y), "len(x) != len(y)"zero_list = [0] * len(x)if x == zero_list or y == zero_list:return float(1) if x == y else float(0)# method 1res = np.array([[x[i] * y[i], x[i] * x[i], y[i] * y[i]] for i in range(len(x))])cos = sum(res[:, 0]) / (np.sqrt(sum(res[:, 1])) * np.sqrt(sum(res[:, 2])))# method 2# cos = bit_product_sum(x, y) / (np.sqrt(bit_product_sum(x, x)) * np.sqrt(bit_product_sum(y, y)))# method 3# dot_product, square_sum_x, square_sum_y = 0, 0, 0# for i in range(len(x)):#     dot_product += x[i] * y[i]#     square_sum_x += x[i] * x[i]#     square_sum_y += y[i] * y[i]# cos = dot_product / (np.sqrt(square_sum_x) * np.sqrt(square_sum_y))return 0.5 * cos + 0.5 if norm else cos  # 归一化到[0, 1]区间内

第一种 调用 sklearn 接口

import sklearn.metrics.pairwise as pwleftfeature = sklearn.preprocessing.normalize(leftfeature)rightfeature= sklearn.preprocessing.normalize(rightfeature)print ("计算cosdistance")  # 调用api接口dis = pw.pairwise_distances(leftfeature, rightfeature, metric='cosine')  # 返回的是什么dis = 1-dis   #cos distance [-1,1] distance = np.empty((len(labels),))  # len(labels)=6000,把返回的值存到distance变量中# print (len(labels))for i in range(len(labels)):distance[i] = dis[i][i]print ('Distance before normalization:\n', distance)print ('Distance max:', np.max(distance), 'Distance min:', np.min(distance), '\n')# 距离需要归一化到0-1,与标签0-1匹配  每个值-最小/最大-最小  ,保证区间在0-1distance_norm = np.empty((len(labels),))for i in range(len(labels)):distance_norm[i] = (distance[i] - np.min(distance)) / (np.max(distance) - np.min(distance))print ('Distance after normalization:\n', distance_norm)# 由distance_norm 和labels 计算精度highestAccuracy, threshold = calculate_accuracy(distance_norm, labels, len(labels))

第二种直接计算得到距离

    g_feats = g_feats / np.sqrt(np.sum(g_feats ** 2, -1, keepdims=True))t_feats = t_feats / np.sqrt(np.sum(t_feats ** 2, -1, keepdims=True))# gallery_label=np.concatenate((test_feats30, test_feats40), axis=0) #拼接### 特征提取结束,进行 比对, top ceshi print("特征的数量维度",img_feats.shape)correct10 = 0correct1= 0for i,line in enumerate(t_feats):  #模型输出line = np.tile(line,(len(g_feats),1))  # repeat 一张图片扩充成所有的维度,用numpy ,方法统一比对dis = np.sum(g_feats * line, 1)  # save index  correspond indexsort_index = np.argsort(-dis, axis=0) #默认 small to large  -dis 从小到大 余弦距离最相似是1,

#然后 pytorch

它们的余弦相似度就是两个特征在经过L2归一化之后的矩阵内积 l2距离计算的就是公式中  A/|A|
得到的距离是 (-1,1),接近1 表示相似,   1-cos  之后范围变成 (2,0),和欧式距离表达的含义一样0表示最相似,
1表示余弦距离的0,基本已经不相似了,所以现在  1-cos是越小越接近,大于1基本不可能相似,也不用特意缩小范围 (0-1)之间,因为(-1,1)之间比0小或者比0.3小的阈值基本不可能相似了。assert metric in ["cosine", "euclidean"], "must choose from [cosine, euclidean], but got {}".format(metric)if metric == "cosine":query_feat = F.normalize(torch.from_numpy(query_features), dim=1)  #gallery_feat = F.normalize(torch.from_numpy(gallery_features), dim=1)dist = 1 - torch.mm(query_feat, gallery_feat.t())  #query 行  gallery 列  的distelse:m, n = query_features.size(0), gallery_features.size(0)xx = torch.pow(torch.from_numpy(query_features), 2).sum(1, keepdim=True).expand(m, n)yy = torch.pow(torch.from_numpy(gallery_features), 2).sum(1, keepdim=True).expand(n, m).t()dist = xx + yydist.addmm_(1, -2, query_features, gallery_features.t())dist = dist.clamp(min=1e-12).sqrt()  # for numerical stability

余弦距离比对对的几种写法 cos距离相关推荐

  1. 唯美伤感个性日志推荐:有一种美因距离而产生

    唯美伤感个性日志推荐:有一种美因距离而产生 - 唯美伤感个性日志推荐:有一种美因距离而产生 有一种美因距离而产生,有一种距离却形成了疏远- 有一种距离很远,却犹如近在咫尺; 有一种距离很近,却又好像远 ...

  2. matlab 高斯模糊_摸鱼 | 茴香豆的“茴”有四种写法,模糊有几种糊法?

    时隔十二天终于等到宋老师的回复后,我拿到了自己的憨憨照片. (后知后觉的宋老师) 刚好考完认知期中(然后三周过去了),便摸个鱼,研究一下Photoshop的使用.今天就整理一下有关模糊的方法. 模糊的 ...

  3. Python:计算欧氏距离的三种写法

    使用列表List作为样本点表示的欧氏距离计算方法: import math # 计算两点之间的距离 def eucliDist(A,B):return math.sqrt(sum([(a - b)** ...

  4. html-css13 flex弹性盒 W3school导航条另一种写法 淘宝的导航条

    flex弹性盒 <!DOCTYPE html> <html lang="en"><head><meta charset="UTF ...

  5. 数据科学中常见的9种距离度量方法,包括欧氏距离、切比雪夫距离、半正矢距离等

    1.欧氏距离(Euclidean Distance) 欧式距离可解释为连接两个点的线段的长度.欧式距离公式非常简单,使用勾股定理从这些点的笛卡尔坐标计算距离. 代码实现: import numpy a ...

  6. 【机器学习基础】常见的9种距离度量方法,内含欧氏距离、切比雪夫距离等

    作者|机器之心编译 来源|机器之心 在数据挖掘中,我们经常需要计算样本之间的相似度,通常的做法是计算样本之间的距离.在本文中,数据科学家 Maarten Grootendorst 向我们介绍了 9 种 ...

  7. K邻近算法概述、欧式距离、Scikit-learn使用 、kNN邻近算法距离度量、曼哈顿距离、切比雪夫距离、闵可夫斯基距离、标准化欧氏距离、余弦距离、汉明距离、杰卡德距离、马氏距离

    一.K-邻近算法概述 K邻近算(K Nearest Neighbor算法,KNN算法):如果一个样本在特征空间中的k个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别,则该样本也属于这个类别 ...

  8. 欧式距离余弦相似度matlab,相似度计算——欧氏距离,曼哈顿距离,闵可夫斯基距离,汉明距离,夹角余弦...

    在机器学习领域,被俗称为距离,却不满足三条距离公理的不仅仅有余弦距离(满足正定性和对称性,但是不满足三角不等式),还有KL距离( Kulback- Leibler Divergence),也叫作相对熵 ...

  9. Javascript闭包和闭包的几种写法及用途

    好久没有写博客了,过了一个十一长假都变懒了,今天总算是恢复状态了.好了,进入正题,今天来说一说javascript里面的闭包吧!本篇博客主要讲一些实用的东西,主要将闭包的写法.用法和用途.  一.什么 ...

最新文章

  1. 全“芯”关注用户需求 AMD“超轻薄笔记本”杀出重围
  2. LeetCode_Convert Sorted Array to Binary Search Tree(Java实现)
  3. [Black Watch 入群题]PWN 栈劫持的利用
  4. html外边距的复合属性是,margin
  5. ORACLE 定时执行存储过程
  6. Action和Func的区别
  7. 分布式与人工智能课程(part15)--深度学习
  8. java流写入数据库_Java 8:在2分钟内将智能流与数据库一起使用
  9. 线段树 洛谷 p1531 I hate it(I hate it too)
  10. 对大脑有益的16种食物_对大脑有益的食物有哪些?
  11. c语言编写的操作系统不会用到类,因为当时c++还没出现
  12. 汇编语言中OUT和IN的用法
  13. 计算机快速看图教程,cad快速看图制图
  14. github安装python包_使用PyCharm从GitHub安装Python包
  15. 请问悉尼大学计算机专业,悉尼大学计算机专业去留学怎么样 是强势专业吗?...
  16. 简单分析2022智能家居现状的优缺点
  17. linux相关操作命令(*)
  18. python pymysql multiprocessing.dummy多线程 读写数据库报错
  19. 你知不知道痛楚的滋味?
  20. 记一次阿里云k8s部署-测试存储

热门文章

  1. Linux Perf性能分析常用手段(火焰图,gprof,kernelshark)
  2. iphone二手价格表
  3. Django数据库报错相关问题总结(初始化、迁移等)
  4. element UI 表格序号倒序
  5. apache服务,或者说httpd服务,如何启动,如何开机启动。
  6. 奢侈品电商逐渐落幕?
  7. 如何使用Date类获取当前时间
  8. IAR编译错误:unable to allocate space for sections/blocks with a total estimated minimum size of 0x504c
  9. 微信域名防封跳转系统详解,域名总是被微信屏蔽应该这样做
  10. Troubleshoot QML Calls of functions that start with an uppercase letter should use ‘new‘. (M306)