【问题标题】:Fastest way to repeat a list of matrices a different number of times重复矩阵列表不同次数的最快方法
【发布时间】:2020-08-05 15:41:21
【问题描述】:

我有一个包含 N 个矩阵的列表,每个矩阵的形状都相同 (dim1,dim2)。 我有另一个 N 个整数列表,说明每个矩阵重复多少次。 创建矩阵列表中每个矩阵的numpy数组的最快方法是什么,根据重复列表重复x次?

例如:

mat_a = np.array([[1, 2],[3, 4]]) # mat_a.shape = (2,2)
mat_b = np.array([[5, 6],[7, 8]]) # mat_b.shape = (2,2)
matrices = [mat_a, mat_b]
repeats = [2, 3]  

result = np.array([mat_a, mat_a, mat_b, mat_b, mat_b]) # results.shape = (5, 2, 2)

我能想到的唯一方法是使用循环,这非常慢:

result = np.array([], dtype=float).reshape(0, 2, 2)
for i in range(len(repeats)):
    result = np.vstack((result, np.tile(matrices[i], (repeats[i], 1, 1))))

【问题讨论】:

  • np.repeat(matrices, repeats, axis=0) 给出正确答案

标签: python numpy


【解决方案1】:

鉴于您在上面定义的变量“矩阵”和“重复”,您需要的是:

result = np.repeat(matrices, repeats, axis=0)

【讨论】:

  • 谢谢,这比使用 for 循环快 10 倍以上。
【解决方案2】:

编辑:现在看看 Shalom Rochman 的更好的解决方案......我不会删除这个,以防仍有任何有用的内容,但显然 np.repeat 是方式去。



这有帮助吗?如果矩阵是一个 numpy 数组:

matrices = np.array([mat_a, mat_b])

你有一个列表[0, 0, 1, 1, 1]

indices = [i for i, n in enumerate(repeats) for _ in range(n)]

然后您可以使用以下方法对其进行索引:

matrices[indices]

这给出了:

array([[[1, 2],
        [3, 4]],

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

       [[5, 6],
        [7, 8]],

       [[5, 6],
        [7, 8]],

       [[5, 6],
        [7, 8]]])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-11
    • 2022-01-19
    • 2023-03-12
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    • 2021-07-19
    相关资源
    最近更新 更多