【问题标题】:How do I create network graph from an adjacency matrix for specific nodes only?如何仅从特定节点的邻接矩阵创建网络图?
【发布时间】:2020-01-04 03:50:43
【问题描述】:

我有一个 5000X5000 的邻接矩阵,我想创建一个网络图。要求是用户将输入节点,输出将是该特定输入节点的图(1st 和 2nd degree)。

我已经尝试过使用 Gephi,但由于邻接矩阵很大,我无法专注于每个节点。所以我想我是否可以为特定节点创建一个图表(因为我只对每个节点的 1 度和 2 度连接感兴趣,而不是除此之外)

Gephi 是基于 UI 的,所以我没有代码。

输入将是一个 node_id,输出将是一个对应于该 node_id 的图(1 度和 2 度连接)

【问题讨论】:

  • 查看 Gephi 拓扑过滤文件夹中的“自我网络”。

标签: python graph networkx gephi


【解决方案1】:

这是一个使用networkx的实现:

import networkx as nx
import numpy as np

# make dummy adjacency matrix
a = np.random.rand(100,100)
a = np.tril(a)
a = a>0.95

# make graph from adjaceny matrix
G = nx.from_numpy_matrix(a)


def neigh(G, node, depth):
    """ given starting node, recursively find neighbours
        until desired depth is reached
    """

    node_list = []
    if depth==0:
        node_list.append(node)
    else:
        for neighbor in G.neighbors(node):
            node_list.append(node)
            node_list += neigh(G, neighbor, depth-1)
    return list(set(node_list)) # intermediate conversion to set to lose duplicates. 

# a bit more compressed:
def neigh_short(G, node, depth):
    """ given starting node, recursively find neighbours
        until desired depth is reached
    """

    node_list = [node]
    if depth>0:
        for neighbor in G.neighbors(node)
            node_list += neigh_short(G, neighbor, depth-1)
    return list(set(node_list)) # intermediate conversion to set to lose duplicates. 

# example:
# find all neighbours with distance 2 from node 5:
n = neigh(G, node=5, depth=2)

# extract the respective subgraph from G and store in H
H = G.subgraph(n)

【讨论】:

  • 感谢您的回复。它达到了我的目的。稍作修正。对于 G.neighbors(node) 中的邻居: node_list.append(neighbor) node_list += neigh(G, neighbor, depth-1) return list(set(node_list)) # 中间转换为 s
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-24
  • 1970-01-01
相关资源
最近更新 更多