我将无向图的边权重保存在行向量中.例如,如果我有一个下图

enter image description here

我创建的向量是[5, 3, 4, 1, 2, 7],按 node 数升序排序.现在,如果我交换 node 1和4的 node 标签,我可以得到下面的图;

enter image description here

在这个场景中,我应该得到的向量是[2, 7, 4, 1, 5, 3]..我的问题是,如果我有一个n×m NumPy的数组,其中n是图的数量,m是边的数量,我如何洗牌每行的 node 标签并有效地获得更新的数组?

假设我有一组由四个 node 组成的图,如下所示.我的意图是随机洗牌每个网络中的 node 标签,然后在相同大小的数组中得到相应的更新权重.

np.random.seed(2)
arr = np.random.randint(10, size=(5, 6))
arr
array([[8, 8, 6, 2, 8, 7],
       [2, 1, 5, 4, 4, 5],
       [7, 3, 6, 4, 3, 7],
       [6, 1, 3, 5, 8, 4],
       [6, 3, 9, 2, 0, 4]])

推荐答案

你可以这样做:

import numpy as np


def get_arr_from_edges(a):
    n = int(np.sqrt(len(a) * 2)) + 1
    mask = np.tri(n, dtype=bool, k=-1).T
    out = np.zeros((n, n))
    out[mask] = a
    out += out.T
    return out


def get_edges_from_arr(a):
    mask = np.tri(a.shape[0], dtype=bool, k=-1).T
    out = a[mask]
    return out


def swap_nodes(a, nodes):
    a[:, [nodes[0] - 1, nodes[1] - 1], :] = a[:, [nodes[1] - 1, nodes[0] - 1], :]
    a[:, :, [nodes[0] - 1, nodes[1] - 1]] = a[:, :, [nodes[1] - 1, nodes[0] - 1]]
    return a


arr = np.array([
        [8, 8, 6, 2, 8, 7],
        [2, 1, 5, 4, 4, 5],
        [7, 3, 6, 4, 3, 7],
        [6, 1, 3, 5, 8, 4],
        [6, 3, 9, 2, 0, 4],
])
nodes_to_swap = (1, 4)

# initialize node-arr
node_arrs = np.apply_along_axis(get_arr_from_edges, axis=1, arr=arr)

# swap nodes
node_arrs = swap_nodes(node_arrs, nodes_to_swap)

# return rempapped edges
edges = np.array([get_edges_from_arr(node_arr) for node_arr in node_arrs])
print(edges)

给出以下结果:

[[8 7 6 2 8 8]
 [4 5 5 4 2 1]
 [3 7 6 4 7 3]
 [8 4 3 5 6 1]
 [0 4 9 2 6 3]]
  • 其思想是从边构建连接矩阵,其中边数保存在两个 node 的索引处.
  • 然后根据要交换的 node 交换列和行.如果希望此过程是随机的,可以创建随机 node 对,并使用这些 node 对多次调用函数.这个过程是非交换的,所以如果你想交换多个 node 对,那么顺序很重要!
  • 然后,读取带有交换列和行的数组的重新映射边(这基本上与第一步相反).

我确信,使用numpys的强大功能还剩下一些优化.

Python相关问答推荐

在上下文管理器中更改异常类型

在应用循环中间保存pandas DataFrame

LAB中的增强数组

运行回文查找器代码时发生错误:[类型错误:builtin_index_or_system对象不可订阅]

难以在Manim中正确定位对象

Pandas 有条件轮班操作

django禁止直接分配到多对多集合的前端.使用user.set()

如何使用pytest来查看Python中是否存在class attribution属性?

Streamlit应用程序中的Plotly条形图中未正确显示Y轴刻度

在Python argparse包中添加formatter_class MetavarTypeHelpFormatter时, - help不再工作""""

删除marplotlib条形图上的底边

isinstance()在使用dill.dump和dill.load后,对列表中包含的对象失败

如何从列表框中 Select 而不出错?

matplotlib + python foor loop

找到相对于列表索引的当前最大值列表""

Cython无法识别Numpy类型

什么是一种快速而优雅的方式来转换一个包含一串重复的列,而不对同一个值多次运行转换,

数据框,如果值在范围内,则获取范围和

如何在Gekko中处理跨矢量优化

类型对象';敌人';没有属性';损害';