【问题标题】:Why does numpy.copy of a numpy.matrix not act like the original matrix? Multiplication with the transpose of that copy does not work为什么 numpy.matrix 的 numpy.copy 不像原始矩阵那样起作用?与该副本的转置相乘不起作用
【发布时间】:2015-11-18 22:07:47
【问题描述】:

我需要处理函数内部的矩阵副本。但是一个副本 (n x 1) 矩阵(向量)的行为不正常。

这里我做了一个例子:

x 与 y 相乘的转置给了我一个正常的向量乘法,其结果为 (1x1) 矩阵。

x 和 y 的副本 a 和 b 不会这样做。他们返回一个维度为 (n x n) 的数组。 我在这里做错了什么?我该如何避免呢?

    >>>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]])

【问题讨论】:

    标签: python numpy matrix


    【解决方案1】:

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

    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) 的等效乘法。

    【讨论】:

      【解决方案2】:

      如果您希望复制矩阵,则不要使用numpy.copy,而是使用matrix 上的copy 方法。

      >>> x = np.matrix('1;3;3')
      >>> x.copy()
      matrix([[1],
              [3],
              [3]])
      

      另一种选择是使用numpy.array(x, copy=True, subok=True)

      请注意,numpy.copy 只是numpy.array(x, copy=True) 的别名,这会导致输入向下转换。

      【讨论】:

        猜你喜欢
        • 2022-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-14
        • 2016-06-28
        • 1970-01-01
        相关资源
        最近更新 更多