日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

实现两个点集的欧式距离和cos距离和索引值寻找(含有两种解法,for循环和矩阵操作)

發布時間:2024/7/23 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 实现两个点集的欧式距离和cos距离和索引值寻找(含有两种解法,for循环和矩阵操作) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一.計算歐式距離

1,直接for循環

兩個點集points1,points2,用dist來存儲距離?

points1=np.array([[1,2],[3,4]]) points2 = np.array([[5, 6],[7,8]]) dist = np.zeros(shape=[points1.shape[0],points2.shape[0]]) for i in range(points1.shape[0]):for j in range(points2.shape[0]):print(points1[i, :] - points2[j, :])

遍歷兩個點集的索引相減值

加上這句話

print(np.square(points1[i, :] - points2[j, :]))

print(np.sum(np.square(points1[i, :] - points2[j, :])))

print(np.sqrt(np.sum(np.square(points1[i, :] - points2[j, :]))))

points1=np.array([[1,2],[3,4]]) points2 = np.array([[5, 6],[7,8]]) dist = np.zeros(shape=[points1.shape[0],points2.shape[0]]) for i in range(points1.shape[0]):for j in range(points2.shape[0]):# print(points1[i, :] - points2[j, :])# print('======================')# print(np.square(points1[i, :] - points2[j, :]))# print('============================')# print(np.sum(np.square(points1[i, :] - points2[j, :])))# print(np.sqrt(np.sum(np.square(points1[i, :] - points2[j, :]))))dist[i, j] = np.sqrt(np.sum(np.square(points1[i, :] - points2[j, :]))) print(dist)

ind = np.unravel_index(np.argmax(dist), dist.shape) print(ind)

返回索引值

2,矩陣操作求歐式距離

假設有兩個三維向量集,用矩陣表示:

要求A,B這兩個矩陣中的元素兩兩之間的歐式距離。

先求出:

然后對和分別求其中每個向量的模平方,并擴展為2*3矩陣:

然后:

?

將上面這個矩陣一開方,就得到了A,B矩陣各個元素兩兩之間的歐式距離。

import numpy as np A=np.array([[1,2],[3,4]]) print('A=',A) B=np.array([[5,6],[7,8]]) print('B=',B)BT=np.transpose(B) print('BT=',BT) A_BT=np.dot(A,BT) print('A_BT=',A_BT)Asq=A**2 Asq=np.tile(np.sum(Asq,axis=1,keepdims=True),(1,A_BT.shape[1])) print('Asq=',Asq)Bsq=BT**2 Bsq=np.tile(np.sum(Bsq,axis=0,keepdims=True),(A_BT.shape[0],1)) print('Bsq=',Bsq)print(Asq+Bsq-2*A_BT) ED=np.sqrt(Asq+Bsq-2*A_BT) print('ED=',ED) ind=np.unravel_index(np.argmax(ED),ED.shape) print(ind) print(ED[ind[0],ind[1])

二.計算cos距離

import numpy as np a = np.array([[1, 2],[3, 4]]) b = np.array([[1, 2],[3, 4],[1, 0]]) c = np.dot(a, np.transpose(b)) print('==c:', c) norm_a = np.sqrt(np.sum(np.square(a), axis=-1)) print('==norm_a:', norm_a) norm_b = np.sqrt(np.sum(np.square(b), axis=-1)) print('==norm_b:', norm_b) base = np.dot(norm_a.reshape(norm_a.shape[0], 1), norm_b.reshape(1, norm_b.shape[0])) print('base:', base) print('===c/base:', c/base)

?

總結

以上是生活随笔為你收集整理的实现两个点集的欧式距离和cos距离和索引值寻找(含有两种解法,for循环和矩阵操作)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。