Der*_*erk 7 python numpy linear-algebra
我转换了以下功能
def quaternion_multiply(quaternion0, quaternion1):
"""Return multiplication of two quaternions.
>>> q = quaternion_multiply([1, -2, 3, 4], [-5, 6, 7, 8])
>>> numpy.allclose(q, [-44, -14, 48, 28])
True
"""
x0, y0, z0, w0 = quaternion0
x1, y1, z1, w1 = quaternion1
return numpy.array((
x1*w0 + y1*z0 - z1*y0 + w1*x0,
-x1*z0 + y1*w0 + z1*x0 + w1*y0,
x1*y0 - y1*x0 + z1*w0 + w1*z0,
-x1*x0 - y1*y0 - z1*z0 + w1*w0), dtype=numpy.float64)
Run Code Online (Sandbox Code Playgroud)
批量版本
def quat_multiply(self, quaternion0, quaternion1):
x0, y0, z0, w0 = np.split(quaternion0, 4, 1)
x1, y1, z1, w1 = np.split(quaternion1, 4, 1)
result = np.array((
x1*w0 + y1*z0 - z1*y0 + w1*x0,
-x1*z0 + y1*w0 + z1*x0 + w1*y0,
x1*y0 - y1*x0 + z1*w0 + w1*z0,
-x1*x0 - y1*y0 - z1*z0 + w1*w0), dtype=np.float64)
return np.transpose(np.squeeze(result))
Run Code Online (Sandbox Code Playgroud)
此函数处理带有形状(?,4)的quaternion1和quaternion0.现在我希望函数可以处理任意数量的维度,例如(?,?,4).这该怎么做?
您只需沿着最后一个轴传递axis-=-1到split即可获得所需的行为。np.split
由于您的数组具有令人讨厌的 size 1 尾随维度,而不是沿着新维度堆叠,然后将其挤压掉,您可以简单地将它们连接起来,再次沿着(最后一个)axis=-1:
def quat_multiply(self, quaternion0, quaternion1):
x0, y0, z0, w0 = np.split(quaternion0, 4, axis=-1)
x1, y1, z1, w1 = np.split(quaternion1, 4, axis=-1)
return np.concatenate(
(x1*w0 + y1*z0 - z1*y0 + w1*x0,
-x1*z0 + y1*w0 + z1*x0 + w1*y0,
x1*y0 - y1*x0 + z1*w0 + w1*z0,
-x1*x0 - y1*y0 - z1*z0 + w1*w0),
axis=-1)
Run Code Online (Sandbox Code Playgroud)
请注意,通过这种方法,您不仅可以乘以任意维数的相同形状的四元数堆栈:
>>> a = np.random.rand(6, 5, 4)
>>> b = np.random.rand(6, 5, 4)
>>> quat_multiply(None, a, b).shape
(6, 5, 4)
Run Code Online (Sandbox Code Playgroud)
但你还可以获得很好的广播,它允许你将一堆四元数与一个四元数相乘,而不必摆弄尺寸:
>>> a = np.random.rand(6, 5, 4)
>>> b = np.random.rand(4)
>>> quat_multiply(None, a, b).shape
(6, 5, 4)
Run Code Online (Sandbox Code Playgroud)
或者用最少的摆弄将两个堆栈之间的所有交叉积放在一行中:
>>> a = np.random.rand(6, 4)
>>> b = np.random.rand(5, 4)
>>> quat_multiply(None, a[:, None], b).shape
(6, 5, 4)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
318 次 |
| 最近记录: |