[英]Fastest way to populate a matrix with a function on pairs of elements in two numpy vectors?
[英]Populate numpy matrix from the difference of two vectors
是否有可能从函数构造一个numpy
矩阵? 在这种情况下,具体地,该函数是两个向量的绝对差: S[i,j] = abs(A[i] - B[j])
。 一个使用常规python的最小工作示例:
import numpy as np
A = np.array([1,3,6])
B = np.array([2,4,6])
S = np.zeros((3,3))
for i,x in enumerate(A):
for j,y in enumerate(B):
S[i,j] = abs(x-y)
赠送:
[[ 1. 3. 5.]
[ 1. 1. 3.]
[ 4. 2. 0.]]
有一个看起来像这样的结构会很好:
def build_matrix(shape, input_function, *args)
我可以用它的参数传递一个输入函数,并保持numpy的速度优势。
除了什么@JoshAdel曾建议,您也可以使用outer
方法的任何numpy的的ufunc
做广播两个数组中的情况。
在这种情况下,你只需要np.subtract.outer(A, B)
(或者更确切地说,它的绝对值)。
虽然这个例子中任何一个都是可读的,但在某些情况下广播更有用,而在其他情况下使用ufunc方法更清晰。
无论哪种方式,了解这两个技巧都很有用。
例如
import numpy as np
A = np.array([1,3,6])
B = np.array([2,4,6])
diff = np.subtract.outer(A, B)
result = np.abs(diff)
基本上,你可以使用outer
, accumulate
, reduce
和reduceat
任何numpy的ufunc
如subtract
, multiply
, divide
,甚至喜欢的东西logical_and
等。
例如, np.cumsum
等同于np.add.accumulate
。 这意味着如果你需要,你可以通过np.divide.accumulate
实现像cumdiv
这样的东西。
我建议看看numpy的广播功能:
In [6]: np.abs(A[:,np.newaxis] - B)
Out[6]:
array([[1, 3, 5],
[1, 1, 3],
[4, 2, 0]])
http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html
然后您可以简单地将您的函数编写为:
In [7]: def build_matrix(func,args):
...: return func(*args)
...:
In [8]: def f1(A,B):
...: return np.abs(A[:,np.newaxis] - B)
...:
In [9]: build_matrix(f1,(A,B))
Out[9]:
array([[1, 3, 5],
[1, 1, 3],
[4, 2, 0]])
这也应该比大型阵列的解决方案快得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.