gpt4 book ai didi

python - numpy - 矩阵多个 3x3 和 100x100x3 数组?

转载 作者:行者123 更新时间:2023-11-30 22:25:03 25 4
gpt4 key购买 nike

我有以下内容:

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 相同的操作?我是否要先以某种方式 reshape 数组?

最佳答案

您似乎正在尝试 sum-reduce XYZ_to_sRGB_mat_D50的最后一个轴(axis=1)XYZ_2 的最后一个(axis=2) 。所以,你可以使用 np.tensordot 就像这样-

np.tensordot(XYZ_2, XYZ_to_sRGB_mat_D50, axes=((2),(1)))

Related post to understand tensordot .


为了完整起见,我们当然可以使用 np.matmul交换 XYZ_2 的最后两个轴后也是如此,就像这样 -

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通过 reshape 数组,使用 np.dot ,得到结果并 reshape 回 3D .

关于python - numpy - 矩阵多个 3x3 和 100x100x3 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47646789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com