输入图表以进行 scipy 图表搜索
Entering the graph for scipy graph search
根据我可以为 scipy graph_search 找到的示例,输入图似乎采用 NxN 形式,其中图的索引对等于该值。
所以一个矩阵
G = [ [0,5,2],
[3,0,8],
[12,7,0] ]
表示2->1
的边权重为索引G[1,0] = 3
的值
如有错误,请说明。
我遇到的问题是以这种方式有效地输入节点连接,从字典开始,其中键是一个节点,值是连接节点的数组。
{'node1' : [node2,weight1],[node3,weight2]}
所在边node1->node2 = weight1
我可以遍历一个键循环并创建一个新的 [ [node1,node2,,weight1],[node1,node3,weight2] ]
数组,但这也不会让我更接近 scipy 格式。有没有一种简单的方法可以从我可以制作的字典或迭代数组中进行这种转换?
假设您已经知道图中节点的数量 N 并且您的图是有向的,您可以这样做:
def create_csgraph_matrix(d, N):
M = np.zeros((N,N))
for i, node_weights in d.items():
for j, weight in node_weights:
M[i, j] = weight
return M
其中 d
是您表单的字典。示例:
In [38]: d = {0: [[1, 10], [2, 20]], 2: [[1, 15]]}
In [39]: create_csgraph_matrix(d,3)
Out[39]:
array([[ 0., 10., 20.],
[ 0., 0., 0.],
[ 0., 15., 0.]])
请注意,此图中的节点是 0,1,2。
根据我可以为 scipy graph_search 找到的示例,输入图似乎采用 NxN 形式,其中图的索引对等于该值。
所以一个矩阵
G = [ [0,5,2],
[3,0,8],
[12,7,0] ]
表示2->1
的边权重为索引G[1,0] = 3
如有错误,请说明。
我遇到的问题是以这种方式有效地输入节点连接,从字典开始,其中键是一个节点,值是连接节点的数组。
{'node1' : [node2,weight1],[node3,weight2]}
所在边node1->node2 = weight1
我可以遍历一个键循环并创建一个新的 [ [node1,node2,,weight1],[node1,node3,weight2] ]
数组,但这也不会让我更接近 scipy 格式。有没有一种简单的方法可以从我可以制作的字典或迭代数组中进行这种转换?
假设您已经知道图中节点的数量 N 并且您的图是有向的,您可以这样做:
def create_csgraph_matrix(d, N):
M = np.zeros((N,N))
for i, node_weights in d.items():
for j, weight in node_weights:
M[i, j] = weight
return M
其中 d
是您表单的字典。示例:
In [38]: d = {0: [[1, 10], [2, 20]], 2: [[1, 15]]}
In [39]: create_csgraph_matrix(d,3)
Out[39]:
array([[ 0., 10., 20.],
[ 0., 0., 0.],
[ 0., 15., 0.]])
请注意,此图中的节点是 0,1,2。