繁体   English   中英

如何从下图中创建邻接矩阵?

[英]How do I create an adjacency matrix from the following graph?

我有以下图表

{
   'start': ['A', 'b'], 
   'A':     ['start', 'c', 'b', 'end'], 
   'b':     ['start', 'A', 'd', 'end'], 
   'c':     ['A'], 
   'd':     ['b'], 
   'end':   ['A', 'b']
}

我想要的邻接矩阵。

邻接矩阵变为:

Excel中的邻接矩阵

我怎样才能做到这一点?


编辑:添加代码以显示进度。 我是这样开始的,但我不知道如何继续,或者它是否是一种好的/可行的方式来做到这一点。

size = (len(graph), len(graph))
adjacency_matrix = np.zeros(shape=size)
for i in range(size[0]):
    for j in range(size[0]):
        if i == j:
            # Diagonals always 0, can't go to oneself from oneself.
            continue
        for node, neighbors in graph.items():
            pass

编辑2:我只是想到以某种方式将特定数字映射到图中的每个节点以便能够在矩阵中识别它们,然后遍历节点边缘并修改矩阵中的适当单元格的想法。 映射的重点是能够在循环时更改矩阵中的单元格。 也许是这样的:

place = {}
for i, node in enumerate(graph.keys()):
    place[node] = i

size = (len(graph), len(graph))
adjacency_matrix = np.zeros(shape=size)
for node, neighbors in graph.items():`
    # Change appropriate cell here
    pass

编辑 3:编辑 2的想法似乎奏效了。 以下代码:

# Part 1
place = {}
for i, node in enumerate(graph.keys()):
    place[node] = i

size = (len(graph), len(graph))
adjacency_matrix = np.zeros(shape=size)
for node, neighbors in graph.items():
    for neighbor in neighbors:
        adjacency_matrix[place[node], place[neighbor]] = 1
print(adjacency_matrix)

生产

[[0. 1. 1. 0. 0. 0.]
 [1. 0. 1. 1. 0. 1.]
 [1. 1. 0. 0. 1. 1.]
 [0. 1. 0. 0. 0. 0.]
 [0. 0. 1. 0. 0. 0.]
 [0. 1. 1. 0. 0. 0.]]

几乎是正确的,第 5 行和第 6 行不正确,在这两种情况下都应该是左边的一个。


编辑 4:编辑 3中的 output 实际上是正确的,我在显示的图片中手动计算了邻接矩阵不正确,因此认为 output 不正确。 讽刺的是,一台电脑在这方面做得比我好。

发布问题后,我设法提出了解决方案。

该解决方案的想法是将 map 每个节点设置为一个唯一编号,该编号将用于在填充邻接矩阵时定位适当的单元格。

identifiers = {node: i for node in enumerate(graph.keys())}

然后填充邻接矩阵的算法变为

size = (len(graph), len(graph))
adjacency_matrix = np.zeros(shape=size)
for node, neighbors in graph.items():
    for neighbor in neighbors:
        adjacency_matrix[place[node], place[neighbor]] = 1

并生成以下对我的图正确的邻接矩阵。

[[0. 1. 1. 0. 0. 0.]
 [1. 0. 1. 1. 0. 1.]
 [1. 1. 0. 0. 1. 1.]
 [0. 1. 0. 0. 0. 0.]
 [0. 0. 1. 0. 0. 0.]
 [0. 1. 1. 0. 0. 0.]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM