我有4个索引为0,1,2和3的点,它们彼此之间都有关系,可以通过网络或下面的二维数组来捕获.我想根据一个阈值将这些数字分组在一起,这样,如果边缘超过阈值,则将这些点分组在一起.

import numpy as np

np.array([[1.0, 0.2, 0.3, 0.4],
          [0.2, 1.0, 0.7, 0.5],
          [0.3, 0.7, 1.0, 0.2],
          [0.4, 0.5, 0.2, 1.0]])

以上示例在不同的阈值下,我的结果将是:

threshold = 0.6
result = [[0], [1,2], [3]]  
#node 0 and 3 connections are all less than the threshold but
#nodes 1 and 2 have an edge of 0.7 which is greater than the threshold.

threshold = 0.8
result = [[0],[1],[2],[3]]

threshold = 0.1

result = [[0,1,2,3]]

我想构建一个函数,它可以用任意N×N矩阵对任意阈值执行此操作.所有边都在01.0之间.对角线将始终为1.0,并且矩阵将始终是对称的,如本例所示.

推荐答案

这是一个图形问题,因此您可以构建一个networkx的加权图形,过滤权重高于阈值的边,并确定connected_components:

import networkx as nx

a = np.array([[1.0, 0.2, 0.3, 0.4],
              [0.2, 1.0, 0.7, 0.5],
              [0.3, 0.7, 1.0, 0.2],
              [0.4, 0.5, 0.2, 1.0]])

G = nx.from_numpy_array(a)

def connected_thresh(G, thresh=0):
    keep = [(u,v) for (u,v,d) in G.edges(data=True)
            if d['weight']>thresh]
    H = G.edge_subgraph(keep)
    return list(nx.connected_components(H))

connected_thresh(G, 0.1)
# [{0, 1, 2, 3}]

connected_thresh(G, 0.6)
# [{0}, {1, 2}, {3}]

connected_thresh(G, 0.8)
# [{0}, {1}, {2}, {3}]

你的图表:

connected components from numpy weight matrix

pre-filtering the edges in

如果您有一个很大的数组作为输入,并且有许多边要移除,则使用NumPy对其进行预处理可能会更有效:

import networkx as nx

out = list(nx.connected_components(nx.from_numpy_array(a>0.6)))

输出:[{0}, {1, 2}, {3}]

图表:

enter image description here

Python-3.x相关问答推荐

使用PANAS根据另两个列表中的值对一个列表中的字符串值进行分组

如何将参数/值从测试方法传递给pytest的fixture函数?

为什么 tkinter 在 tkinter 窗口外计算鼠标事件?

以特定方式重新排列 pandas 数据框的列

从另一个云函数调用带有仅允许内部流量标志的云函数时出现问题

基于组/ID从原始数据框中创建两个子数据框

Python,Web 从交互式图表中抓取数据

提高时间复杂度的一些建议

Semaphore信号量 Python 的工作原理

在 jupyter notebook 的单元格中使用 sudo

Python 3 list(dictionary.keys()) 引发错误.我究竟做错了什么?

获取嵌套字典的所有键

为什么我在 Python 中收到错误消息无法导入名称 NoneType?

asyncio.Semaphore RuntimeError: Task got Future 附加到不同的循环

django - 值更改后自动更新日期

使用 Sublime Text 3 在 Python 3 中打印 UTF-8

从大字典中弹出 N 项的最快方法

Python的max函数有多高效

在 Python 3 中调用 super() 的 4 种方法中的哪一种?

Python 3 中的连接列表