当前位置:网站首页>cosine 相似度计算总结
cosine 相似度计算总结
2022-06-10 23:56:00 【qq_45759229】
随机产生数据
import torch
import numpy as np
xx=np.random.randn(4,5)
yy=np.random.randn(7,5)
# xx=np.array([[1,2,3],[2,3,4]])
# yy=np.array([[2,1,2],[4,2,1],[3,3,3]])
x=torch.from_numpy(xx).type(torch.float64)
y=torch.from_numpy(yy).type(torch.float64)
#cosine_sim(x,y)
cosine相似度计算方法1
res1=np.zeros((xx.shape[0],yy.shape[1]))
for i in range(xx.shape[0]):
for j in range(yy.shape[1]):
ii=xx[i]
jj=yy[j]
res1[i,j]=np.dot(ii,jj)/np.sqrt(sum(ii**2))/np.sqrt(sum(jj**2))
print(res1)
结果如下
cosine相似度计算方法2
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity, paired_distances
res2=cosine_similarity(xx,yy)
print(res2)
结果如下
cosine相似度计算方法3
import torch
import numpy as np
def cosine_sim(x, y):
x = x / torch.norm(x, dim=1, keepdim=True)
y = y / torch.norm(y, dim=1, keepdim=True)
sim = torch.matmul(x, torch.transpose(y, 0, 1))
return sim
x=torch.from_numpy(xx).type(torch.float64)
y=torch.from_numpy(yy).type(torch.float64)
res3=cosine_sim(x,y)
print(res3)
结果如下
cosine相似度计算方法4
import torch.nn.functional as F
C = F.cosine_similarity(x.unsqueeze(1), y, dim=-1)
print(C)
print(C.shape)
# torch.size([2,10])
结果如下
cosine相似度计算方法5
from scipy.spatial.distance import cdist
res5=1-cdist(xx,yy,metric="cosine") # 先计算距离,再计算相似度
print(res5)
结果如下
特殊情况1,计算pair_X和pair_Y之间对应的cosine相似度(待补充)
# ##
# # Import the required library
# import torch
# # define two input tensors
# tensor1 = torch.randn(3,4)
# tensor2 = torch.randn(3,4)
# # print above defined two tensors
# print("Tensor 1:\n", tensor1)
# print("Tensor 2:\n", tensor2)
# # define a method to measure cosine similarity in dim 0
# cos0 = torch.nn.CosineSimilarity(dim=0)
# output0 = cos0(tensor1, tensor2)
# print("Cosine Similarity in dim 0:\n",output0)
# # define a method to measure cosine similarity in dim 1
# cos1 = torch.nn.CosineSimilarity(dim=1)
# output1 = cos1(tensor1, tensor2)
# print("Cosine Similarity in dim 1:\n",output1)
# import torch.nn as nn
# input1 = torch.randn(10, 128)
# input2 = torch.randn(10, 128)
# cos = nn.CosineSimilarity(dim=1, eps=1e-6)
# output = cos(input1, input2)
# print(output)
# xx=input1.numpy()
# yy=input2.numpy()
# from scipy.spatial.distance import cdist
# output2=cdist(xx,yy,metric="cosine")
# output2
特殊情况2,计算自身X与X的cosine相似度(待补充)
##
##
边栏推荐
- 自动化测试系列
- About log traffic monitoring and early warning small project | flag log monitoring script
- Can I buy annuity insurance? Is annuity insurance safe?
- 【ROS入门教程】---- 03 ROS基本概念及指令
- Introduction and basic construction of kubernetes
- Complete uninstallation of MySQL under Linux
- 启牛商学院中信建投账户怎么样?安全吗
- Pirate OJ 148 String inversion
- 年金险还能买吗?年金险安不安全?
- Objects as points personal summary
猜你喜欢

Dictionary sort of array

The principle and source code interpretation of executor thread pool in concurrent programming

Logback log framework

海贼oj#146.字符串

【ROS入门教程】---- 03 ROS基本概念及指令

Kubernetes入门介绍与基础搭建

lucene思维导图,让搜索引擎不再难懂

Blocking queue - delayedworkqueue source code analysis

What is MYCAT? Get to know you quickly

Signature verification failed during system application installation
随机推荐
海贼oj#146.字符串
Logback log framework
Win11 uninstall widget
About log traffic monitoring and early warning small project | database management tool: migrate
systemd 下开机启动的优化,删除无用的systemd服务
WIN11卸载小组件
亿级搜索系统(优酷视频搜索)的基石,如何保障实时数据质量?v2020
Dynamic programming classical topic triangle shortest path
QT program plug-in reports an error plugin xcb
How word inserts a guide (dot before page number) into a table of contents
oracle带xy字段值的关系表同步到pg数据库转为几何字段
负载均衡策略图文详解
Unable to return to the default page after page Jump
招聘 | 南京 | TRIOSTUDIO 三厘社 – 室内设计师 / 施工图深化设计师 / 装置/产品设计师 / 实习生等
SqlServer中的鎖
How to install mathtype6.9 and related problem solutions in office2016 (word2016)
Slam Kalman filter & nonlinear optimization
[network planning] 1.3 packet switching and circuit switching in the network core
About log traffic monitoring and early warning small project | flask
自动化测试系列