【问题标题】:Vectorization of this Numpy double loop这个 Numpy 双循环的向量化
【发布时间】:2011-11-28 17:35:45
【问题描述】:

如何向量化以下双循环?

我有一个 N 乘 A 矩阵和一个 N 乘 B 矩阵,其中 A 和 B 可能不同,并且 N 比 A 和 B 小得多。我想按如下方式生成 A 乘 B 矩阵,但理想情况下没有循环:

import numpy as np

def foo(arr):
    # can be anything - just an example so that the code runs
    return np.sum(arr)

num_a = 12
num_b = 8
num_dimensions = 3

a = np.random.rand(num_dimensions, num_a)
b = np.random.rand(num_dimensions, num_b)

# this is the loop I want to eliminate:
output = np.zeros( (num_a, num_b) )
for i in xrange(num_a):
    for j in xrange(num_b):
       output[i,j] = foo(a[:,i] - b[:,j])

有什么想法吗?

【问题讨论】:

    标签: python numpy linear-algebra


    【解决方案1】:

    首先向量化foo(),即修改foo(),使其可以正确操作形状为(N, A, B)的数组,返回形状为(A, B)的数组。这一步通常是困难的一步。这如何完成完全取决于foo() 做了什么。对于给定的示例,这很容易做到:

    def foo(arr):
        return np.sum(arr, axis=0)
    

    现在,使用broadcasting rules 创建一个包含所有向量差异的(N, A, B) 数组,并将其传递给foo()

    foo(a[:, :, np.newaxis] - b[:, np.newaxis])
    

    【讨论】:

    • 谢谢,我从中学到了很多。在我的全部问题上,矢量化版本的速度也令人难以置信。前 231 秒,后 2 秒!
    猜你喜欢
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 2013-07-21
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多