矢量化函数以在NetworkX图上运行

时间:2016-01-28 05:18:03

标签: python numpy networkx

我有一个n阶DiGraph。我也有一个(n x n)numpy数组。我想在numpy数组上应用一个函数。此功能是基于NetworkX的功能。下面给出一个小例子:

G = nx.DiGraph()
eList = [('1','2'), ('1', '4'), ('2','3'), ('3','1'), ('4', '5'), ('5', '4')]
G.add_edges_from(eList)

myMatrix = np.zeros((5, 5))

def myFunc(i, j, G):
    s = np.min(G.in_degree(str(i)), G.in_degree(str(j)))/np.max(G.in_degree(str(i)), G.in_degree(str(j)))
    return s

现在,我如何申请' myFunc'在myMatrix'的所有细胞上?我不知道该怎么做。

fv = np.vectorize(myFunc)

然后......不确定如何调用它。目前,我是以一种相当笨拙的方式做到这一点:

for (i, j), value in np.ndenumerate(myMatrix):
    s = np.min(G.in_degree(str(i)), G.in_degree(str(j)))/np.max(G.in_degree(str(i)), G.in_degree(str(j)))
    myMatrix[i, j] = s
    return myMatrix

我担心在大矩阵上循环很糟糕,因此想要尝试向量化。

1 个答案:

答案 0 :(得分:1)

您可以像这样使用numpy.fromfunction

from __future__ import division
import networkx as nx
import numpy as np

G = nx.DiGraph([('1','2'), ('1', '4'), ('2','3'), ('3','1'), ('4', '5'), ('5', '4')])
d = dict(G.in_degree())
n = len(d)

def myfunc(i,j):
    di = d[str(i+1)]
    dj = d[str(j+1)]
    return min(di,dj)/max(di,dj)

f = np.vectorize(myfunc)
a = np.fromfunction(f, (n,n), dtype=int)
print a

[[ 1.   1.   1.   0.5  1. ]
 [ 1.   1.   1.   0.5  1. ]
 [ 1.   1.   1.   0.5  1. ]
 [ 0.5  0.5  0.5  1.   0.5]
 [ 1.   1.   1.   0.5  1. ]]