此函数将n
的每个pose
行乘以不同的旋转矩阵。是否可以通过使用3d张量的旋转矩阵来避免循环?
def transform(ref, pose):
n, d = pose.shape
p = ref[:, :d].copy()
c = np.cos(ref[:, 2])
s = np.sin(ref[:, 2])
for i in range(n):
p[i,:2] += pose[i,:2].dot(np.array([[c[i], s[i]], [-s[i], c[i]]]))
return p
这是np.einsum
的一个 -
# Setup 3D rotation matrix
cs = np.empty((n,2,2))
cs[:,0,0] = c
cs[:,1,1] = c
cs[:,0,1] = s
cs[:,1,0] = -s
# Perform 3D matrix multiplications with einsum
p_out = ref[:, :d].copy()
p_out[:,:2] += np.einsum('ij,ijk->ik',pose[:,:2],cs)
或者,替换c
的两个指定步骤,其中一个涉及一个einsum
-
np.einsum('ijj->ij',cs)[...] = c[:,None]
在optimize
中使用True
标志和np.einsum
值来利用BLAS
。
或者,我们可以使用np.matmul/@ operator in Python 3.x
来取代einsum
部分 -
p_out[:,:2] += np.matmul(pose[:,None,:2],cs)[:,0]