【问题标题】:compute a xi-xj matrix in numpy without loops (by api calls)在没有循环的numpy中计算一个xi-xj矩阵(通过api调用)
【发布时间】:2015-01-26 23:17:32
【问题描述】:

如何在没有循环的情况下在 numpy 中计算 xi-xj 矩阵(通过 api 调用)?

从这里开始:

import numpy as np
x = np.random.rand(4)
xij = np.matrix([xi-xj for xj in x for xi in x]).reshape(4,4)

【问题讨论】:

    标签: python numpy matrix vectorization


    【解决方案1】:

    您可以利用广播从作为平面数组的x 中减去作为列向量的x 并生成矩阵。

    >>> x = np.random.rand(4)
    

    然后:

    >>> x - x[:,np.newaxis]
    array([[ 0.        ,  0.89175647,  0.80930233,  0.37955823],
           [-0.89175647,  0.        , -0.08245415, -0.51219825],
           [-0.80930233,  0.08245415,  0.        , -0.4297441 ],
           [-0.37955823,  0.51219825,  0.4297441 ,  0.        ]])
    

    如果你想要一个矩阵对象(而不是默认数组对象),你可以这样写:

    np.matrix(x - x[:,np.newaxis])
    

    【讨论】:

      【解决方案2】:

      通过重塑数组,你可以使用减号运算符来计算你想要的

      import numpy as np
      x = np.random.rand(4)
      x = x.reshape(-1,1)
      xij = np.matrix(x.T - x)
      

      【讨论】:

      • 您可以跳过矩阵类的reshape 步骤,因为所有矩阵本质上都是二维的。 x = np.matrix(np.random.rand(4)); x - x.T.
      • 这对我来说是新的。我倾向于避免使用 matrix 类,因为如果你不小心(当 *-operator 没有按照你期望的那样做时),它会咬你一口。
      【解决方案3】:

      另一种选择是使用np.subtract.outer

      In [35]: x = np.random.rand(4)
      
      In [36]: np.matrix([xi-xj for xj in x for xi in x]).reshape(4,4)
      Out[36]: 
      matrix([[ 0.        ,  0.45365177,  0.07227472, -0.05824887],
              [-0.45365177,  0.        , -0.38137705, -0.51190064],
              [-0.07227472,  0.38137705,  0.        , -0.13052359],
              [ 0.05824887,  0.51190064,  0.13052359,  0.        ]])
      
      In [37]: -np.subtract.outer(x, x)
      Out[37]: 
      array([[-0.        ,  0.45365177,  0.07227472, -0.05824887],
             [-0.45365177, -0.        , -0.38137705, -0.51190064],
             [-0.07227472,  0.38137705, -0.        , -0.13052359],
             [ 0.05824887,  0.51190064,  0.13052359, -0.        ]])
      

      (请注意,结果是一个numpy数组,而不是矩阵。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多