gpt4 book ai didi

python - 如何有效地将矩阵变换应用于 NumPy 数组的每一行?

转载 作者:太空宇宙 更新时间:2023-11-03 12:28:04 25 4
gpt4 key购买 nike

假设我有一个 2d NumPy ndarray,如下所示:

[[ 0, 1, 2, 3 ],
[ 4, 5, 6, 7 ],
[ 8, 9, 10, 11 ]]

从概念上讲,我想做的是:

For each row:
Transpose the row
Multiply the transposed row by a transformation matrix
Transpose the result
Store the result in the original ndarray, overwriting the original row data

我有一个非常慢的蛮力方法,它在功能上实现了这个:

import numpy as np
transform_matrix = np.matrix( /* 4x4 matrix setup clipped for brevity */ )
for i, row in enumerate( data ):
tr = row.reshape( ( 4, 1 ) )
new_row = np.dot( transform_matrix, tr )
data[i] = new_row.reshape( ( 1, 4 ) )

但是,这似乎是 NumPy 应该擅长的操作。我假设 - 作为 NumPy 的新手 - 我只是缺少文档中的一些基本内容。有什么指点吗?

请注意,如果创建一个新的 ndarray 比就地编辑它更快,那也适用于我正在做的事情;操作速度是首要考虑因素。

最佳答案

您要执行的一系列冗长操作等同于以下内容:

data[:] = data.dot(transform_matrix.T)

或者使用一个新的数组而不是修改原来的数组,这样应该会快一点:

data.dot(transform_matrix.T)

解释如下:

For each row:
Transpose the row

相当于转置矩阵,然后遍历列。

    Multiply the transposed row by a transformation matrix

将矩阵的每一列左乘第二个矩阵等同于将整个矩阵左乘第二个矩阵。此时,您拥有的是 transform_matrix.dot(data.T)

    Transpose the result

矩阵转置的基本属性之一是 transform_matrix.dot(data.T).T 等价于 data.dot(transform_matrix.T)

    Store the result in the original ndarray, overwriting the original row data

切片分配就是这样做的。

关于python - 如何有效地将矩阵变换应用于 NumPy 数组的每一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20512833/

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