NetworkX:当我将 'weight' 添加到某个节点时,我无法生成 adjacecy_matrix()?

NetworkX : When I add 'weight' to some node I can not generatee adjacecy_matrix()?

当我将 'weight' 添加到节点时,我无法再生成 adjacency_matrix() ?关于如何仍然能够生成它的任何想法?

In [73]: g2 = nx.Graph()

In [74]: g2.add_path([1,2,3,5,4,3,1,4,3,7,2])

In [75]: nx.adjacency_matrix(g2)
Out[75]: 
matrix([[ 0.,  1.,  1.,  1.,  0.,  0.],
    [ 1.,  0.,  1.,  0.,  0.,  1.],
    [ 1.,  1.,  0.,  1.,  1.,  1.],
    [ 1.,  0.,  1.,  0.,  1.,  0.],
    [ 0.,  0.,  1.,  1.,  0.,  0.],
    [ 0.,  1.,  1.,  0.,  0.,  0.]])

In [76]: g2[3]['weight'] = 5

In [77]: nx.adjacency_matrix(g2)
---------------------------------------------------------------------------
 AttributeError                            Traceback (most recent call last)
 <ipython-input-77-532c786b4588> in <module>()
 ----> 1 nx.adjacency_matrix(g2)

/usr/lib/pymodules/python2.7/networkx/linalg/graphmatrix.pyc in  adjacency_matrix(G, nodelist, weight)
     144     to_dict_of_dicts
     145     """
--> 146     return nx.to_numpy_matrix(G,nodelist=nodelist,weight=weight)
    147 
    148 adj_matrix=adjacency_matrix

/usr/lib/pymodules/python2.7/networkx/convert.pyc in to_numpy_matrix(G, nodelist, dtype, order, multigraph_weight, weight)
    522             for v,d in nbrdict.items():
    523                 try:
--> 524                     M[index[u],index[v]]=d.get(weight,1)
    525                 except KeyError:
    526                     pass

AttributeError: 'int' object has no attribute 'get'

同样适用于:

 In [79]: nx.adjacency_matrix(g2,weight='weight')

你很接近 - 将节点权重分配给 g2.node[2]['weight'] 它将起作用。

请注意,节点权重不会出现在邻接矩阵中。这是在那里分配的边缘权重。例如

In [1]: import networkx as nx

In [2]: g2 = nx.Graph()

In [3]: g2.add_path([1,2,3,5,4,3,1,4,3,7,2])

In [4]: g2.node[2]['weight']=7

In [5]: g2.node
Out[5]: {1: {}, 2: {'weight': 7}, 3: {}, 4: {}, 5: {}, 7: {}}

In [6]: nx.adjacency_matrix(g2).todense()
Out[6]: 
matrix([[0, 1, 1, 1, 0, 0],
        [1, 0, 1, 0, 0, 1],
        [1, 1, 0, 1, 1, 1],
        [1, 0, 1, 0, 1, 0],
        [0, 0, 1, 1, 0, 0],
        [0, 1, 1, 0, 0, 0]])

In [7]: g2.edge[1][2]['weight'] = 42

In [8]: nx.adjacency_matrix(g2).todense()
Out[8]: 
matrix([[ 0, 42,  1,  1,  0,  0],
        [42,  0,  1,  0,  0,  1],
        [ 1,  1,  0,  1,  1,  1],
        [ 1,  0,  1,  0,  1,  0],
        [ 0,  0,  1,  1,  0,  0],
        [ 0,  1,  1,  0,  0,  0]])

您还会看到我正在使用生成稀疏矩阵的较新版本的 networkx,因此我添加了 .todense() 方法来获取密集 (numpy) 矩阵。