![](/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.