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

use*_*880 3 python arrays numpy multidimensional-array

假设我有一个2d NumPy ndarray,就像这样:

[[ 0, 1, 2, 3 ],
 [ 4, 5, 6, 7 ],
 [ 8, 9, 10, 11 ]]
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

我有一个极其缓慢,强力的方法,在功能上实现了这一点:

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 ) )
Run Code Online (Sandbox Code Playgroud)

然而,这似乎是NumPy应该做的那种操作.我认为 - 作为NumPy的新手 - 我只是遗漏了文档中的一些基本内容.有什么指针吗?

请注意,如果创建新的ndarray更快,而不是就地编辑它,那么这也适用于我正在做的事情; 操作速度是首要关注的问题.

use*_*ica 10

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

data[:] = data.dot(transform_matrix.T)
Run Code Online (Sandbox Code Playgroud)

或使用新数组而不是修改原始数据,这应该更快一点:

data.dot(transform_matrix.T)
Run Code Online (Sandbox Code Playgroud)

这是解释:

For each row:
    Transpose the row
Run Code Online (Sandbox Code Playgroud)

相当于转置矩阵然后越过列.

    Multiply the transposed row by a transformation matrix
Run Code Online (Sandbox Code Playgroud)

将矩阵的每列左乘第二矩阵相当于将整个事物左乘第二矩阵.在这一点上,你拥有的是什么transform_matrix.dot(data.T)

    Transpose the result
Run Code Online (Sandbox Code Playgroud)

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

    Store the result in the original ndarray, overwriting the original row data
Run Code Online (Sandbox Code Playgroud)

切片分配执行此操作.