基于近邻点索引的稀疏矩阵到稠密矩阵转换
1. 问题来源
在代码编写过程中,我们经常遇到这种情况, 已经获取了每个点的近邻点和近邻关系, 下一步就是转换成稠密矩阵进行后续计算. 在这一过程中,我们通常会使用两层 for 循环来完成, 而对于 matlab 或者 python 会变得非常低效, 于是我们可以利用矩阵计算的方式避免出现 for 循环, 从而达到高效的代码实现.
2. 算法设计
3. 代码实现
def sparse2dense(Neighborhood,Sim):
d,N = Neighborhood.shape # 输入近邻矩阵列数为样本点数,每一列代表该点近邻点的索引
d1,N1 = Sim.shape
if d != d1 and N != N1:
print('Error: The two matrices must have the same shape!')
d,N = Neighborhood.shape
# 构造本征点的索引矩阵,形状与近邻索引矩阵相同
ind = np.arange(0,N).reshape(1,-1) # 为本征点样本设置索引,并存储为行
index = np.ones((d,1))@ind # 构造与近邻索引矩阵形状相同的本征点索引矩阵
Index = index.astype(int) # 将索引格式强制转换成整数
X = np.zeros((N,N))
X[Index,Neighborhood] = Sim
return X
import numpy as np
if __name__ == '__main__':
Neighborhood = np.array([[1,2,1,2,1],[3,4,2,3,3]])# 每个样本点的 2-近邻索引
Sim = np.array([[1,1,1,1,1],[1,1,1,1,1]]) # 每个样本点
Similarity = sparse2dense(Neighborhood,Sim)
print('近邻索引矩阵为:\n{}\n'.format(Neighborhood))
print('近邻相似度矩阵为:\n{}\n'.format(Sim))
print('稠密邻接矩阵为:\n{}\n'.format(Similarity))
输出结果
近邻索引矩阵为:
[[1 2 1 2 1]
[3 4 2 3 3]]
近邻相似度矩阵为:
[[1 1 1 1 1]
[1 1 1 1 1]]
稠密邻接矩阵为:
[[0. 1. 0. 1. 0.]
[0. 0. 1. 0. 1.]
[0. 1. 1. 0. 0.]
[0. 0. 1. 1. 0.]
[0. 1. 0. 1. 0.]]