python效率numpy,在Python(NumPy)中高效计算相似度矩阵

这篇博客探讨了如何在Python中利用NumPy库高效地计算相似度矩阵,特别是当涉及RBF函数时。作者提出了一个使用scipy.spatial.distance.cdist的方法,以及一个仅使用NumPy数组操作的解决方案。
摘要由CSDN通过智能技术生成

Let X be a Bxn numpy matrix, i.e.,

import numpy as np

B = 10

n = 2

X = np.random.random((B, n))

Now, I'm interested in computing the so-called kernel (or even similarity) matrix K, which is of shape BxB, and its {i,j}-th element is given as follows:

K(i,j) = fun(x_i, x_j)

where x_t denotes the t-th row of matrix X and fun is some function of x_i, x_j. For instance, this function could be the so-called RBF function, i.e.,

K(i,j) = exp(-|x_i - x_j|^2).

For doing so, a naive way would be the following:

K = np.zeros((B, B))

for i in range(X.shape[0]):

x_i = X[i, :]

for j in range(X.shape[0]):

x_j = X[j, :]

K[i, j] = np.exp(-np.linalg.norm(x_i - x_j, 2) ** 2)

What I want is to do the above operation in a vectorized way, for the sa

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值