将每一行乘以不同的旋转矩阵
Multiply each row by different rotation matrix
此函数将 pose
的 n
行中的每一行乘以不同的旋转矩阵。是否可以通过使用旋转矩阵的 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
标志和 np.einsum
中的 True
值来利用 BLAS
。
或者,我们可以使用 np.matmul/@ operator in Python 3.x
来替换 einsum
部分 -
p_out[:,:2] += np.matmul(pose[:,None,:2],cs)[:,0]
此函数将 pose
的 n
行中的每一行乘以不同的旋转矩阵。是否可以通过使用旋转矩阵的 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
标志和 np.einsum
中的 True
值来利用 BLAS
。
或者,我们可以使用 np.matmul/@ operator in Python 3.x
来替换 einsum
部分 -
p_out[:,:2] += np.matmul(pose[:,None,:2],cs)[:,0]