2015-11-13 138 views
3

得到鄰居矩陣我有給定無向圖:Numpy-從二維數組

A,B 
A,C 
A,F 
B,D 
C,D 
C,F 
E,D 
E,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', 'F'], 
     ['B', 'D'], 
     ['C', 'D'], 
     ['C', 'F'], 
     ['E', 'D'], 
     ['E', 'F']], 
     dtype='|S4') 

預期輸出:

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

由於

+0

已存儲的圖形怎麼辦?考慮爲我們添加樣本輸入數據。 – Divakar

+0

@Divakar請看看我添加的NOTA,謝謝你的問題 – farhawa

+2

另外,你可以添加預期的輸出嗎? – Divakar

回答

3

這裏有一個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()+1 
idx1 = 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 indices 
np.put(out,[idx1,idx2],1) 

樣品輸入,輸出 - 對性能迄今列出

In [93]: graph 
Out[93]: 
array([['A', 'B'], 
     ['A', 'C'], 
     ['A', 'F'], 
     ['B', 'D'], 
     ['C', 'D'], 
     ['C', 'F'], 
     ['E', 'D'], 
     ['E', 'F']], 
     dtype='|S4') 

In [94]: out 
Out[94]: 
array([[1, 1, 1, 0, 0, 1], 
     [1, 1, 0, 1, 0, 0], 
     [1, 0, 1, 1, 0, 1], 
     [0, 1, 1, 1, 1, 0], 
     [0, 0, 0, 1, 1, 1], 
     [1, 0, 1, 0, 1, 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[:,0],s[:,1]] = 1 
    res_sym = res + res.T 
    np.fill_diagonal(res_sym,1) 
    return res_sym 

def unique_based(graph): #solution from this post 
    _,ID = np.unique(graph,return_inverse=True) 
    M = ID.reshape(graph.shape) 
    n = M.max()+1 
    idx1 = M[:,0]*(n) + M[:,1] 
    idx2 = M[:,1]*(n) + M[:,0] 
    out = np.eye(n,dtype=int) 
    np.put(out,[idx1,idx2],1) 
    return out 

計時 -

In [321]: N = 1000 

In [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 loop 

In [325]: %timeit vectorize_based(graph) 
1000 loops, best of 3: 760 µs per loop 

In [326]: %timeit unique_based(graph) 
1000 loops, best of 3: 405 µs per loop 
+0

謝謝@Divakar你的答案,請你給你的解決方案添加一些評論?它的功能非常神奇,但是我對python很陌生,恐怕我無法理解你完全做了什麼;)謝謝 – farhawa

+0

@farhawa看看添加的評論是否有助於你理解那裏發生了什麼。 – Divakar

3

使用networkx

A=nx.Graph() 
for x in a: 
    A.add_edge(x[0],x[1]) 
ad =nx.adjacency_matrix(A) 

matrix([[ 0., 1., 1., 0., 0., 1.], 
     [ 1., 0., 0., 0., 1., 1.], 
     [ 1., 0., 0., 0., 1., 0.], 
     [ 0., 0., 0., 0., 1., 1.], 
     [ 0., 1., 1., 1., 0., 0.], 
     [ 1., 1., 0., 1., 0., 0.]]) 

推薦fill_diagonal,以獲得自我的鏈接,在你的預期輸出:

np.fill_diagonal(ad,1) 

matrix([[ 1., 1., 1., 0., 0., 1.], 
     [ 1., 1., 0., 1., 0., 0.], 
     [ 1., 0., 1., 1., 0., 1.], 
     [ 0., 1., 1., 1., 1., 0.], 
     [ 0., 0., 0., 1., 1., 1.], 
     [ 1., 0., 1., 0., 1., 1.]]) 
+0

對不起,我不能顯示矩陣,我得到這個:''type'numpy.int64'>' \t'類型'1x6稀疏矩陣與壓縮稀疏行格式的3個存儲元素> ' – farhawa

+0

@farhawa爲我工作,蟒蛇2.7,numpy 1.8.0,網絡x 1.8.1 – atomh33ls

1

在純numpy我會做類似

import numpy as np 

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

# define vectorized mapping from letters to integers 
ord_u = np.vectorize(lambda x: ord(x)-65) 

# map entities of data to integer 
s = ord_u(data) 

# initialize the matrix 
res = np.zeros((s.max()+1,s.max()+1)) 

# use advanced indexing for calculating the matrix 
res[s[:,0],s[:,1]] = 1 

# symmetrize the matrix 
res_sym = res + res.T 
np.fill_diagonal(res_sym,1) 

res_sym 
#array([[ 1., 1., 1., 0., 0., 1.], 
#  [ 1., 1., 0., 1., 0., 0.], 
#  [ 1., 0., 1., 1., 0., 1.], 
#  [ 0., 1., 1., 1., 1., 0.], 
#  [ 0., 0., 0., 1., 1., 1.], 
#  [ 1., 0., 1., 0., 1., 1.]])