[英]Efficiently create affinity matrix numpy
I currently use this code to compute an affinity matrix我目前使用此代码来计算亲和力矩阵
m = np.size(pts[0])
A = np.zeros(m*m).reshape(m,m)
for i,x in enumerate(pts[0]):
for j,y in enumerate(pts[1]):
A[i,j] = np.exp(-1*np.linalg.norm(x-y)**2)
Where pts is a nx2 matrix.其中 pts 是一个 nx2 矩阵。 This works fine on smaller size but is O(n^2).这适用于较小的尺寸,但为 O(n^2)。 The result should be a nxn matrix with the weights.结果应该是一个带有权重的 nxn 矩阵。
Here's a vectorized version:这是一个矢量化版本:
#n = 10
#pts = np.random.rand(2, n)
X, Y = np.meshgrid(pts[1], pts[0])
A = np.exp(-np.abs(X-Y)**2) # you can omit the abs because of **2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.