首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用特征和邻接矩阵的数值表示建立networkx/dgl图

用特征和邻接矩阵的数值表示建立networkx/dgl图
EN

Stack Overflow用户
提问于 2021-02-11 05:43:43
回答 1查看 719关注 0票数 0

描述

从邻接矩阵生成图形对象( DGL或NetworkX),并允许建立节点特征。

结果

我在下面生成我的解决方案。然而,其他答案也是值得鼓励的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-11 05:43:43

代码

代码语言:javascript
运行
复制
import numpy as np
import dgl
import networkx as nx

def numpy_to_graph(A,type_graph='dgl',node_features=None):
    '''Convert numpy arrays to graph

    Parameters
    ----------
    A : mxm array
        Adjacency matrix
    type_graph : str
        'dgl' or 'nx'
    node_features : dict
        Optional, dictionary with key=feature name, value=list of size m
        Allows user to specify node features

    Returns

    -------
    Graph of 'type_graph' specification
    '''
    
    G = nx.from_numpy_array(A)
    
    if node_features != None:
        for n in G.nodes():
            for k,v in node_features.items():
                G.nodes[n][k] = v[n]
    
    if type_graph == 'nx':
        return G
    
    G = G.to_directed()
    
    if node_features != None:
        node_attrs = list(node_features.keys())
    else:
        node_attrs = []
        
    g = dgl.from_networkx(G, node_attrs=node_attrs, edge_attrs=['weight'])
    return g

示例

邻接矩阵被传递给函数。此外,其他特征(即特征向量、标签等)可以在node_features中传递

代码语言:javascript
运行
复制
# mxm adjacency matrix
A = np.array([[0,0,0],
              [2,0,0],
              [5,1,0]])

# Each m row is a feature vector for node m
F = np.array([[1,0,1,4,4],
             [2,4,0,12,4],
             [5,1,-4,2,9]])


G = numpy_to_graph(A,type_graph='nx',node_features={'feat':F})

import matplotlib.pyplot as plt
pos=nx.spring_layout(G) # pos = nx.nx_agraph.graphviz_layout(G)
nx.draw_networkx(G,pos)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
plt.show()

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66145521

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档