【问题标题】:Is there a more efficient way to find the average of a large number of matrices?有没有更有效的方法来找到大量矩阵的平均值?
【发布时间】:2018-07-30 01:07:09
【问题描述】:

所以我现在有大约 300 个矩阵,这还不错,但我想让我的代码在未来可重用,所以我想知道是否有更有效的方法来找到平均值。我拥有的矩阵是 88x88,我想要平均它的方式是在最后得到一个矩阵,其中每个 [i][j] 值是另一个中所有 [i][j] 值的平均值300 个矩阵。

mean = []
smaller = []


for j in range(88):
        for i in range(88):
            for k in range(len(listof_matrices)):
                smaller.append(listof_matrices[k][i][j])
                mean.append(str(float(sum(smaller))/float(len(smaller))))

基本上,代码的工作方式是 3 个嵌套循环(我知道...),它首先在所有 k 个矩阵中附加单个 [i][j] 位置的值,找到平均值,然后将其添加到平均值list 存储它,并为所有 i 和所有 j 再次执行此操作。肯定有更快的方法。干杯

【问题讨论】:

  • numpy 是你的朋友。 np.mean(listof_matrices, axis=0)
  • @Julien 即使我的矩阵不是 numpy 数组而只是普通列表,它也能工作吗?还是应该将它们全部转换为 numpy 数组?
  • 在大多数情况下,numpy 会自动为您转换。

标签: python python-2.7 matrix


【解决方案1】:

一定要使用numpy。我会用一个可重现的例子给你解释

Setup

m1 = np.array([[3, 6, 2], [5, 6, 3], [2, 7, 2]])
m2 = np.array([[1, 5, 7], [9, 9, 8], [1, 6, 6]])
m3 = np.array([[9, 8, 3], [3, 5, 4], [7, 3, 3]])
list_of_matrices = [m1, m2, m3]

Solution

那就用np.mean

np.mean(list_of_matrices, axis=0)

输出

array([[4.33333333, 6.33333333, 4.        ],
       [5.66666667, 6.66666667, 5.        ],
       [3.33333333, 5.33333333, 3.66666667]])

因此,对于您的示例,您可能需要做的唯一loop 就是创建list_of_matrices,无论如何您都必须这样做。然后,您只需调用np.mean,它将使用矢量化解决方案生成您的均值矩阵。时间会非常比你的三嵌套循环方法快。

【讨论】:

    【解决方案2】:

    您真的应该将numpy 用于这些目的。

    假设您将矩阵放在一个 numpy 数组中。示例:

    import numpy as np
    
    matrix = np.array([
        [
            [1, 2],
            [3, 4]
        ],
        [
            [5, 6],
            [7, 8]
        ],
        [
            [9, 10],
            [11, 12]
        ],
    ])
    

    你可以得到平均值

    np.sum(matrix, axis=0)/float(matrix.shape[0])
    

    np.sum(matrix, axis=0) 将所有数组的最外轴相加,matrix.shape[0] 为您提供其中包含的矩阵数量。

    另外,numpy 的性能比原始 python 的性能要很多好得多

    【讨论】:

    • 为什么不只是 np.mean
    猜你喜欢
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 2014-02-22
    • 2021-08-30
    • 1970-01-01
    相关资源
    最近更新 更多