爲避免重新發明輪子,應按照註釋和其他答案中的建議使用networkx。
如果出於教育目的,你想想要重新發明輪子,你可以創建一個adjacency matrix。可以從該矩陣計算PageRank:
PageRank值是修改後的鄰接矩陣的主導右特徵向量的條目。
由於鄰接矩陣中的每個行/列代表一個節點,則需要枚舉節點,以便每個節點通過從0
import numpy as np
data = np.array([['P01106', 'Q09472'],
['P01106', 'Q13309'],
['P62136', 'Q13616'],
['P11831', 'P18146'],
['P13569', 'P20823'],
['P20823', 'P01100']])
nodes = np.unique(data) # mapping node name --> index
noidx = {n: i for i, n in enumerate(nodes)} # mapping node index --> name
n = nodes.size # number of nodes
numdata = np.vectorize(noidx.get)(data) # replace node id by node index
A = np.zeros((n, n))
for tail, head in numdata:
A[tail, head] = 1
#A[head, tail] = 1 # add this line for undirected graph
這導致開始一個唯一的編號表示以下圖形表示A
:
array([[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 1., 1., 0.],
[ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
A 1在5行,例如第0列意味着存在從節點5到節點0-5的邊緣,其對應於'P20823'
- >'P01100'
。使用nodes
陣列從索引中查找節點名稱:
print(nodes)
['P01100' 'P01106' 'P11831' 'P13569' 'P18146' 'P20823' 'P62136' 'Q09472'
'Q13309' 'Q13616']
如果有很多節點和連接數,最好使用sparse matrix
爲A
。但是,首先嚐試使用密集矩陣,只是懶得改用稀疏的存儲器或性能問題。
你有沒有考慮過使用'networkx'?您可以輕鬆地將您的陣列轉換爲邊緣列表。 – DyZ