![](/img/trans.png)
[英]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.