我有兩個稀疏二進制矩陣A,B它們具有匹配的維度,例如A具有 shapeI x J和Bshape J x K。我有一個自定義動作的結果以矩陣C形狀的I x J x K,其中每個元素(i,j,k)是1僅當A(i,j) = 1 and B(j,k) = 1。我目前已按如下方式實施此操作:
import numpy as np
I = 2
J = 3
K = 4
A = np.random.randint(2, size=(I, J))
B = np.random.randint(2, size=(J, K))
# Custom method
C = np.zeros((I,J,K))
for i in range(I):
for j in range(J):
for k in range(K):
if A[i,j] == 1 and B[j,k] == 1:
C[i,j,k] = 1
print(C)
但是,for 回圈對于 large 來說很慢I,J,K。是否可以僅使用 numpy 方法來實作此操作以加快速度?我看過np.multiply.outer,但到目前為止沒有成功。
uj5u.com熱心網友回復:
干得好:
C = np.einsum('ij,jk->ijk', A,B)
uj5u.com熱心網友回復:
嘗試用 numba 做你已經在做的事情。這是使用您的代碼、Sehan2 的方法和 numba 的示例:
import numpy as np
from numba import jit, prange
I = 2
J = 3
K = 4
np.random.seed(0)
A = np.random.randint(2, size=(I, J))
B = np.random.randint(2, size=(J, K))
# Custom method
def Custom_method(A, B):
I, J = A.shape
J, K = B.shape
C = np.zeros((I,J,K))
for i in range(I):
for j in range(J):
for k in range(K):
if A[i,j] == 1 and B[j,k] == 1:
C[i,j,k] = 1
return C
def Custom_method_ein(A, B):
C = np.einsum('ij,jk->ijk', A,B)
return C
@jit(nopython=True)
def Custom_method_numba(A, B):
I, J = A.shape
J, K = B.shape
C = np.zeros((I,J,K))
for i in prange(I):
for j in prange(J):
for k in prange(K):
if A[i,j] == 1 and B[j,k] == 1:
C[i,j,k] = 1
return C
print('original')
%timeit Custom_method(A, B)
print('einsum')
%timeit Custom_method_ein(A, B)
print('numba')
%timeit Custom_method_numba(A, B)
輸出:
original
10000 loops, best of 5: 18.8 μs per loop
einsum
The slowest run took 20.51 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 5: 3.32 μs per loop
numba
The slowest run took 15.99 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 5: 815 ns per loop
請注意,如果您使用稀疏矩陣表示,您可以使您的代碼運行得更快、更高效。這樣您就可以避免執行不必要的操作。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/338754.html
