Numpy 双循环的向量化

发布于 2024-12-18 13:24:02 字数 572 浏览 0 评论 0原文

如何矢量化以下双循环?

我有一个 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])

任何想法?

How can I vectorize the following double-loop?

I have one N by A matrix and one N by B matrix, where A and B may differ and N is much smaller than A and B. I want to produce an A by B matrix as follows, but ideally without the loops:

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])

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冰火雁神 2024-12-25 13:24:02

首先对 foo() 进行向量化,即修改 foo() 使其能够正确地对形状为 (N, A, B) 的数组进行操作code>,返回形状为 (A, B) 的数组。这一步通常是最困难的一步。如何完成此操作完全取决于 foo() 的作用。对于给定的示例,这很容易做到:

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

现在,使用 广播规则< /a> 创建一个包含所有向量差异的 (N, A, B) 数组,并将其传递给 foo()

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

First vectorise foo(), i.e. modify foo() in a way that it can correctly operate on an array of shape (N, A, B), returning an array of shape (A, B). This step is usually the difficult one. How this is done entirely depends on what foo() does. For the given example, it's very easy to do:

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

Now, use broadcasting rules to create a (N, A, B) array containing all the vector differences, and pass it to foo():

foo(a[:, :, np.newaxis] - b[:, np.newaxis])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文