假设我有一个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
切片分配执行此操作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句