python – Numpy-从2D数组获取邻居矩阵

python – Numpy-从2D数组获取邻居矩阵,第1张

概述我有一个无向图,由下式给出: A,BA,CA,FB,DC,DC,FE,DE,F 我需要将其转换为矩阵N,其中 N[x,y] = 1 if x is neighbor of y (like A and B) and 0 if not 最快的方法是什么? NOTA图表存储为numpy字符串数组: array([['A', 'B'], ['A', 'C'], [ 我有一个无向图,由下式给出:

A,BA,CA,FB,DC,FE,DE,F

我需要将其转换为矩阵N,其中

N[x,y] = 1 if x is neighbor of y (like A and B) and 0 if not

最快的方法是什么?

NOTA图表存储为numpy字符串数组:

array([['A','B'],['A','C'],'F'],['B','D'],['C',['E','F']],dtype='|S4')

预期产量:

A B C D E FA  1 1 1 0 0 1B  1 1 0 1 0 0 C  1 0 1 1 0 1D  0 1 1 1 1 0E  0 0 0 1 1 1 F  1 0 1 0 1 1

谢谢

解决方法 这是一种NumPythonic方法 –

# Tag each string with a numeric ID based on the uniqueness among other strings_,ID = np.unique(graph,return_inverse=True)M = ID.reshape(graph.shape)# ConsIDer each row of numeric IDs as an indexing tuple of a 2D array.# Calculate the linear indices corresponding to each tuple.n = M.max()+1IDx1 = M[:,0]*(n) + M[:,1]IDx2 = M[:,1]*(n) + M[:,0]# Setup output array with 1s on the diagonal.out = np.eye(n,dtype=int)# Put 1s at places specifIEd by the earlIEr computed pairs of linear indicesnp.put(out,[IDx1,IDx2],1)

样本输入,输出 –

In [93]: graphOut[93]: array([['A',dtype='|S4')In [94]: outOut[94]: array([[1,1,1],[1,0],[0,1]])

运行时测试

本节基本上比较了迄今为止列出的所有方法(在这篇文章和其他帖子中)解决案例的表现.

定义功能 –

def networkx_based(a): #@atomh33ls's solution code    A=nx.Graph()    for x in a:        A.add_edge(x[0],x[1])    return nx.adjacency_matrix(A)def vectorize_based(data): # @plonser's solution code    ord_u = np.vectorize(lambda x: ord(x)-65)    s = ord_u(data)    res = np.zeros((s.max()+1,s.max()+1),dtype=int)    res[s[:,s[:,1]] = 1    res_sym = res + res.T    np.fill_diagonal(res_sym,1)    return res_symdef unique_based(graph): #solution from this post    _,return_inverse=True)    M = ID.reshape(graph.shape)    n = M.max()+1    IDx1 = M[:,1]    IDx2 = M[:,0]    out = np.eye(n,dtype=int)    np.put(out,1)    return out

计时 –

In [321]: N = 1000In [322]: arr = np.random.randint(65,90,(N,2))In [323]: graph = np.array([map(chr,a) for a in arr],dtype='S4')In [324]: %timeit networkx_based(graph)100 loops,best of 3: 3.79 ms per loopIn [325]: %timeit vectorize_based(graph)1000 loops,best of 3: 760 µs per loopIn [326]: %timeit unique_based(graph)1000 loops,best of 3: 405 µs per loop
总结

以上是内存溢出为你收集整理的python – Numpy-从2D数组获取邻居矩阵全部内容,希望文章能够帮你解决python – Numpy-从2D数组获取邻居矩阵所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1193551.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存