加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 12:23:40 所属栏目:Python 来源:网络整理
导读:假设我有一个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 o
假设我有一个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

切片分配执行此操作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读