[英]How do I vectorized these two numpy operations without using for loop?
there is an operation in numpy I've found hard to implement without looping numpy 中有一个操作我发现没有循环很难实现
That operation is that I have two inputs: beta,x
该操作是我有两个输入: beta,x
beta.shape = (M,N,K)
and x.shape = (I,K)
beta.shape = (M,N,K)
和x.shape = (I,K)
The operation I'm interested in can be done using for loop as follows我感兴趣的操作可以使用for循环完成如下
result = np.zeros((M,N,I,K)) # buffer to save my operation results
for m in range(M):
for n in range(N):
beta_ = beta[m][n] # has shape (K,)
result[m][n] = x * beta_
Let tricks here that I can do without loops so that the whole operation can be computational efficient?让我可以在没有循环的情况下做一些技巧,以便整个操作可以高效计算?
You're interested in multiplying the elements across the common K dimension, and keeping the results along the remaining dimensions.您有兴趣在公共 K 维度上乘以元素,并将结果保持在其余维度上。
This means you can use np.einsum
using the dimensions of beta, x, and the shape result you're interested in like 'mnk,ik->mnik'
:这意味着您可以使用np.einsum
使用 beta、x 的尺寸以及您感兴趣的形状结果,例如'mnk,ik->mnik'
:
import numpy as np
M = 4
N = 3
I = 7
K = 6
beta = np.arange(M*N*K).reshape(M,N,K)
x = np.arange(I*K).reshape(I,K)
result1 = np.zeros((M,N,I,K)) # buffer to save my operation results
for m in range(M):
for n in range(N):
beta_ = beta[m][n] # has shape (K,)
result1[m][n] = x * beta_
result2 = np.einsum('mnk,ik->mnik', beta, x)
print (np.array_equal(result1,result2))
True
Not part of the question but while talking about np.einsum
... If you want to sum across any of these dimensions, you can omit it from the end dimensions:不是问题的一部分,但在谈论np.einsum
...如果您想对这些维度中的任何一个求和,您可以从最终维度中省略它:
import numpy as np
M = 4
N = 3
I = 7
K = 6
beta = np.arange(M*N*K).reshape(M,N,K)
x = np.arange(I*K).reshape(I,K)
result1 = np.zeros((M,N,I,K)) # buffer to save my operation results
for m in range(M):
for n in range(N):
beta_ = beta[m][n] # has shape (K,)
result1[m][n] = x * beta_
result1 = result1.sum(axis=1)
result2 = np.einsum('mnk,ik->mik', beta, x)
print (np.array_equal(result1,result2))
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.