【问题标题】:Method to split a SciPy minimum spanning tree based on greatest edge weight?基于最大边权重分割 SciPy 最小生成树的方法?
【发布时间】:2014-08-15 07:29:01
【问题描述】:

有没有办法通过删除树中最大的边权重值来拆分scipy.sparse.csgraph.minimum_spanning_tree 操作的输出?我正在尝试访问每个子树,如果该边不是最小生成树的外边,则会通过丢弃最大边权重来获得。

使用 SciPy 文档示例:

from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import minimum_spanning_tree
X = csr_matrix([[0, 8, 0, 3],
                [0, 0, 2, 5],
                [0, 0, 0, 6],
                [0, 0, 0, 0]])
Tcsr = minimum_spanning_tree(X)
# print(Tcsr)
# (0,3) 3.0
# (3,1) 5.0
# (1,2) 2.0

在上面的最小生成树中删除中间值并分别访问其他两条边的最佳方法是什么?我正在尝试在大型图表上执行此操作,并尽可能避免大型 Python 循环。谢谢。

【问题讨论】:

  • 你有没有找到解决办法?

标签: python numpy scipy minimum-spanning-tree


【解决方案1】:

我遇到了同样的问题,并设法仅使用 scipy 找到了解决方案。所做的只是获取 MST,找到最大加权边,将其删除(即归零),然后使用 connected_components 方法找出哪些节点保持连接。

这是带有 cmets 的完整脚本:

import numpy as np
from scipy.sparse.csgraph import minimum_spanning_tree, connected_components
from scipy.sparse import csr_matrix

# Create a random "distance" matrix.
# Select only the upper triangle since the distance matrix array would be symmetrical.
a = np.random.rand(5,5)
a = np.triu(a)

# Create the minimum spanning tree.
mst = minimum_spanning_tree(csr_matrix(a))
mst = mst.toarray()

# Get the index of the maximum value.
# `argmax` returns the index of the _flattened_ array;
# `unravel_index` converts it back.
idx = np.unravel_index(mst.argmax(), mst.shape)

# Clear out the maximum value to split the tree.
mst[idx] = 0

# Label connected components.
num_graphs, labels = connected_components(mst, directed=False)

# We should have two trees.
assert(num_graphs == 2)

# Use indices as node ids and group them according to their graph.
results = [[] for i in range(max(labels) + 1)]
for idx, label in enumerate(labels):
    results[label].append(idx)

print(results)

这将产生类似:

[[0, 1, 4], [2, 3]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 2012-05-11
    • 1970-01-01
    相关资源
    最近更新 更多