numpy-矩阵多个3x3和100x100x3阵列? [英] numpy - matrix multiple 3x3 and 100x100x3 arrays?
问题描述
我有以下内容:
import numpy as np
XYZ_to_sRGB_mat_D50 = np.asarray([
[3.1338561, -1.6168667, -0.4906146],
[-0.9787684, 1.9161415, 0.0334540],
[0.0719453, -0.2289914, 1.4052427],
])
XYZ_1 = np.asarray([0.25, 0.4, 0.1])
XYZ_2 = np.random.rand(100,100,3)
np.matmul(XYZ_to_sRGB_mat_D50, XYZ_1) # valid operation
np.matmul(XYZ_to_sRGB_mat_D50, XYZ_2) # makes no sense mathematically
如何在XYZ_2上执行与在XYZ_2上相同的操作?我会以某种方式首先重塑数组吗?
How do I perform the same operation on XYZ_2 that I would on XYZ_2? Do I somehow reshape the array first?
推荐答案
似乎您正在尝试sum-reduce
XYZ_to_sRGB_mat_D50
(axis=1)
的最后一个轴与XYZ_2
(axis=2)
的最后一个轴.因此,您可以使用 np.tensordot
像这样-
It seems you are trying to sum-reduce
the last axis of XYZ_to_sRGB_mat_D50
(axis=1)
with the last one of XYZ_2
(axis=2)
. So, you can use np.tensordot
like so -
np.tensordot(XYZ_2, XYZ_to_sRGB_mat_D50, axes=((2),(1)))
为完整起见,在交换XYZ_2
的最后两个轴之后,我们当然也可以使用np.matmul
-
For completeness, we can surely use np.matmul
too after swappping last two axes of XYZ_2
, like so -
np.matmul(XYZ_to_sRGB_mat_D50, XYZ_2.swapaxes(1,2)).swapaxes(1,2)
这不会像tensordot
那样高效.
运行时测试-
In [158]: XYZ_to_sRGB_mat_D50 = np.asarray([
...: [3.1338561, -1.6168667, -0.4906146],
...: [-0.9787684, 1.9161415, 0.0334540],
...: [0.0719453, -0.2289914, 1.4052427],
...: ])
...:
...: XYZ_1 = np.asarray([0.25, 0.4, 0.1])
...: XYZ_2 = np.random.rand(100,100,3)
# @Julien's soln
In [159]: %timeit XYZ_2.dot(XYZ_to_sRGB_mat_D50.T)
1000 loops, best of 3: 450 µs per loop
In [160]: %timeit np.tensordot(XYZ_2, XYZ_to_sRGB_mat_D50, axes=((2),(1)))
10000 loops, best of 3: 73.1 µs per loop
通常来说,关于张量上的sum-reductions
时,tensordot
的效率要高得多.由于sum-reduction
的轴只有一个,因此我们可以通过重整形来使张量成为2D
数组,使用np.dot
,获取结果并将其重整为3D
.
Generally speaking, when it comes to sum-reductions
on tensors, tensordot
is much more efficient. Since, the axis of sum-reduction
is just one, we can make the tensor a 2D
array by reshaping, use np.dot
, get the result and reshape back to 3D
.
这篇关于numpy-矩阵多个3x3和100x100x3阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!