NumPy Matrix操作,无需复制 [英] NumPy Matrix operation without copying

查看:61
本文介绍了NumPy Matrix操作,无需复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如何在不复制矩阵对象的情况下进行矩阵转置?同样,和其他矩阵运算一样(从矩阵中减去一个矩阵,...).这样做有好处吗?

How I can make, for example, matrix transpose, without making a copy of matrix object? As well, as other matrix operations ( subtract a matrix from the matrix, ...). Is it beneficial to do that?

推荐答案

进行数组转置不会产生副本:

Taking the transpose of an array does not make a copy:

>>> a = np.arange(9).reshape(3,3)
>>> b = np.transpose(a)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> b
array([[0, 3, 6],
       [1, 4, 7],
       [2, 5, 8]])
>>> b[0,1] = 100
>>> b
array([[  0, 100,   6],
       [  1,   4,   7],
       [  2,   5,   8]])
>>> a
array([[  0,   1,   2],
       [100,   4,   5],
       [  6,   7,   8]])

同样适用于numpy.matrix对象.

The same applies to a numpy.matrix object.

当您要避免通过复制非常大的数组而不必要地消耗大量内存时,此 可能会很有用.但是,在修改转置时,还必须注意避免无意间修改原始数组(如果仍然需要).

This can be beneficial when you want to avoid unnecessarily consuming a lot of memory by copying very large arrays. But you also have to be careful to avoid unintentionally modifying the original array (if you still need it) when you modify the transpose.

许多numpy函数接受可选的"out"关键字(例如numpy.dot),以将输出写入现有数组.例如,要获取a与其自身的矩阵乘积,并将输出写入现有数组c:

A number of numpy functions accept an optional "out" keyword (e.g., numpy.dot) to write the output to an existing array. For example, to take the matrix product of a with itself and write the output an existing array c:

numpy.dot(a, a, out=c)

这篇关于NumPy Matrix操作,无需复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆