矩阵距离——计算高维样本之间的距离

前言

关于这部分,我自己并没有很懂,目前网上找到的资料和博客,我并没有完全领会,所以这篇博客只能算是学习过程的简略版。(以后更懂再更新)

计算矩阵距离

矩阵距离——计算高维样本之间的距离
函数 返回 任意两个点之间距离的平方
import numpy as np
def cal_parwise_dist(x):

    sum_x = np.sum(np.square(x), 1)

    dist = np.add(np.add(-2 * np.dot(x, x.T), sum_x).T, sum_x)

    return dist

扩展了解

参考链接
内容截图:

矩阵距离——计算高维样本之间的距离
上述推导对应公式,python实现
def f(A,B):
    m = np.shape(A)[0]
    n = np.shape(B)[0]
    dists = np.zeros((m, n))

    M = np.dot(A, B.T)
    H1 = np.square(A).sum(axis=1)
    H2 = np.square(B).sum(axis=1)
    D = np.sqrt(-2 * M + H1 + np.matrix(H2).T)
    return np.square(D)

python补充

其中值得注意的是

1、 数据type 类型

import numpy as np
X = np.array(range(1,13)).reshape(4,3)
sum_x = np.sum(np.square(X),1)
print(sum_x,'类型',type(sum_x))
print(sum_x.T,'类型',type(sum_x.T))
print(np.matrix(sum_x).T,'类型',type(np.matrix(sum_x).T))

输出结果,截图如下:

矩阵距离——计算高维样本之间的距离

sum_x与sum_x.T输出结果是一致的。因为此时sum_x是一维数组,一维数组使用.T并不能实现转置。而np.matrix(sum_x).T属于矩阵转置,故实现转置。

dist = np.add(np.add(-2 * np.dot(x, x.T), sum_x).T, sum_x)

2、转置部分居然不影响结果?

def cal_parwise_dist(x):

    sum_x = np.sum(np.square(x), 1)

    dist1 = np.add(np.add(-2 * np.dot(x, x.T), sum_x).T, sum_x)
    print(dist1)
    dist2 = np.add(np.add(-2 * np.dot(x, x.T), sum_x), np.matrix(sum_x).T)
    print(dist2)

dist1和dist2 两者居然输出结果一致,是因为都是对同一个矩阵X进行相加,所以np.add(-2 * np.dot(x, x.T), sum_x).T转置,还是np.matrix(sum_x).T转置,相加结果都一致。可以理解为上述《扩展了解》部分的f(A,B)函数中A,B矩阵一样,同为X矩阵,所以前部分转置,还是后部分转置的结果都是一样的。

3、为什么要转置?

上面表示任意两点距离的平方的函数中用下面的表达式:
(a-b)^2 = a^2 + b^2 – 2 _a_b
或者下面的矩阵推导公式表示:

矩阵距离——计算高维样本之间的距离
但关于代码实现中要进行转置,我就很迷惑……(希望有懂的好兄弟可以评论分享一下啦~)
可以理解为: 要将H2展开到D上的每一列,需要转置成列向量。因为本身H1计算出来是行向量

Original: https://blog.csdn.net/weixin_46021869/article/details/116711725
Author: shallow不秃头
Title: 矩阵距离——计算高维样本之间的距离

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/762855/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球