Numpy 双循环的向量化
如何矢量化以下双循环?
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先对
foo()
进行向量化,即修改foo()
使其能够正确地对形状为(N, A, B)
的数组进行操作code>,返回形状为(A, B)
的数组。这一步通常是最困难的一步。如何完成此操作完全取决于 foo() 的作用。对于给定的示例,这很容易做到:现在,使用 广播规则< /a> 创建一个包含所有向量差异的
(N, A, B)
数组,并将其传递给foo()
:First vectorise
foo()
, i.e. modifyfoo()
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 whatfoo()
does. For the given example, it's very easy to do:Now, use broadcasting rules to create a
(N, A, B)
array containing all the vector differences, and pass it tofoo()
: