本文介绍了为什么 numpy.matrix 的 numpy.copy 不像原始矩阵?与该副本的转置相乘不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要处理函数内的矩阵副本.但是一个副本(n x 1) 矩阵(向量)的行为不像它应该的那样.

I need to work with copys of matrices inside functions. But the copy of a(n x 1) matrix (vector) doesn't behave like it should.

这里我举了一个例子:

x 乘以 y 的转置给了我一个正常的向量乘法,结果是一个 (1x1) 矩阵.

Transpose of x multiplied with y gives me a normal vector-multiplication with an outcome of a (1x1)-matrix.

x 和 y 的副本 a 和 b 不会这样做.他们返回一个维度为 (n x n) 的数组.我在这里做错了什么?我怎么能避免这种情况?

The copys a and b of x and y won't do that. They give back an array with dimension (n x n).What am I doing wrong here? And how could I avoid that?

    >>>import numpy as np

    >>>x=np.matrix('1;2;3')
    >>>y=np.matrix('1;1;-1')

    >>>x.T*y
    matrix([[0]])

    >>>a=np.copy(x)
    >>>b=np.copy(y)

    >>>a.T*b
    array([[ 1,  2,  3],
           [ 1,  2,  3],
           [-1, -2, -3]])

推荐答案

您的原始数组属于子类 matrix.副本是基本的 array 类.使用 x.copy(),特定于矩阵类的复制方法来创建另一个矩阵.然后矩阵乘法运算将像以前一样工作.

Your original arrays are of subclass matrix. The copy is the base array class. Use x.copy(), the copy method specific to the matrix class to make another matrix. Then the matrix multiplication operations will work as before.

In [52]: x=np.matrix('1;3;3')
In [53]: x
Out[53]: 
matrix([[1],
        [3],
        [3]])
In [54]: np.copy(x)
Out[54]: 
array([[1],
       [3],
       [3]])
In [55]: x.copy()
Out[55]: 
matrix([[1],
        [3],
        [3]])

另一个答案中提出的解决方案是将 matrix 乘法替换为 np.array (np.dot) 的等效乘法.

The solution proposed in the other answer is to replace the matrix multiplications with the equivalent ones for np.array (np.dot).

这篇关于为什么 numpy.matrix 的 numpy.copy 不像原始矩阵?与该副本的转置相乘不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 22:32