![](/img/trans.png)
[英]how to multiply a numpy column array of size N to row array of size N in python to get N X N matrix?
[英]Transforming a 3 Column Matrix into an N x N Matrix in Numpy
我有3列的2D numpy
数组。 第1列和第2列是ID之间的连接列表。 第3栏是这种联系的力量。 我想将此3列矩阵转换为加权邻接矩阵 (N x N矩阵,其中单元代表每个ID之间的连接强度)。
我已经在下面的代码中完成了此操作。 matrix
是3列2D数组, t1
是加权邻接矩阵。 我的问题是这段代码非常慢,因为我使用嵌套的for循环。 我对执行此操作的pandas
函数melt
,但是我不能使用pandas
。 是否有不使用pandas
的更快实现?
import numpy as np
a = np.arange(2000)
np.random.shuffle(a)
b = np.arange(2000)
np.random.shuffle(b)
c = np.random.rand(2000,1)
matrix = np.column_stack((a,b,c))
#get unique value list of nm
flds = list(np.unique(matrix[:,0]))
flds.extend(list(np.unique(matrix[:,1])))
flds = np.asarray(flds)
flds = np.unique(flds)
#make lookup dict
lookup = dict(zip(np.arange(0,len(flds)), flds))
lookup_rev = dict(zip(flds, np.arange(0,len(flds))))
#make empty n by n matrix with unique lists
t1 = np.zeros([len(flds) , len(flds)])
#map values into the n by n matrix and make the rest 0
'''this takes a long time to run'''
#iterate through rows
for i in np.arange(0,len(lookup)):
#iterate through columns
for k in np.arange(0,len(lookup)):
val = matrix[(matrix[:,0] == lookup[i]) & (matrix[:,1] == lookup[k])][:,2]
if val:
t1[i,k] = sum(val)
假设我正确理解了这个问题,并且val
是一个标量,则可以使用矢量化方法,该方法涉及用zeros
初始化,然后进行indexing
,如下所示:
out = np.zeros((len(flds),len(flds)))
out[matrix[:,0].astype(int),matrix[:,1].astype(int)] = matrix[:,2]
请注意,根据我的观察,您似乎可以避免使用lookup
。
您可以获得的主要加速效果是,不对NxN矩阵的每个元素进行迭代,而是对连接列表进行迭代,该连接列表要小得多。
我试图简化您的代码。 它使用list.index
方法,该方法可能很慢,但仍应比您拥有的方法快。
import numpy as np
a = np.arange(2000)
np.random.shuffle(a)
b = np.arange(2000)
np.random.shuffle(b)
c = np.random.rand(2000,1)
matrix = np.column_stack((a,b,c))
lookup = np.unique(matrix[:,:2]).tolist() # You can call unique only once
t1 = np.zeros((len(lookup),len(lookup)))
for i,j,val in matrix:
t1[lookup.index(i),lookup.index(j)] = val # Fill the matrix
您只需要迭代一次矩阵:
import numpy as np
size = 2000
a = np.arange(size)
np.random.shuffle(a)
b = np.arange(size)
np.random.shuffle(b)
c = np.random.rand(size,1)
matrix = np.column_stack((a,b,c))
#get unique value list of nm
fields = np.unique(matrix[:,:2])
n = len(fields)
#make reverse lookup dict
lookup = dict(zip(fields, range(n)))
#make empty n by n matrix
t1 = np.zeros([n, n])
for src, dest, val in matrix:
i = lookup[src]
j = lookup[dest]
t1[i, j] += val
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.