python - 使用 Numpy 向量化 for 循环

标签 python numpy

我有一个 for 循环,我想用 numpy 对其进行矢量化。在下面的代码片段中,RAdone 是长度为 num_rows 的 numpy 数组,而 Q 和 Q1是大小为(num_rows, num_cols)的矩阵。另外值得注意的是,A 的所有元素都在 0num_cols - 1 之间,并且 done 的所有元素都在01。我基本上想做与下面的 for 循环相同的事情,但利用 numpy 矢量化。

重要信息:

  • R 是长度为 num_rows 的 numpy 数组。任意值
  • A 是长度为 num_rows 的 numpy 数组。值可以是 0 到 num_cols - 1
  • 之间的整数
  • done 是一个长度为 num_rows 的 numpy 数组。值为 0 或 1
  • Q 是一个形状为 (num_rows, num_cols) 的 2D numpy 数组
  • Q1 也是一个形状为 (num_rows, num_cols) 的 2D numpy 数组

这是循环:

    y = np.zeros((num_rows, num_cols))

    for i in range(num_rows):
        r = R[i]
        a = A[i]
        q = Q[i]
        adjustment = r
        if not done[i]:
            adjustment += (gamma*max(Q1[i]))
        q[a] = adjustment
        y[i, :] = q

我认为我已经通过以下几行以矢量化方式获得了“调整”,我只需要对 Q 矩阵进行赋值并输出正确的 y矩阵。

这些是我用来矢量化第一部分的行:

    q_max_adjustments = np.multiply(gamma * Q1.max(1), done) # This would be numpy array of length num_rows
    true_adjustments = R + q_max_adjustments # Same dimension numpy array

输入和输出的示例是

gamma = 0.99
R = numpy.array([1,2,0,3,2])
A = numpy.array([0,2,0,1,1])
done = numpy.array([0,1,0,0,1])
Q = numpy.array([[1,2,3],
                 [4,5,6],
                 [7,8,9],
                 [10,11,12],
                 [13,14,15]])
Q1 = numpy.array([[1,2,3],
                 [4,5,6],
                 [7,8,9],
                 [10,11,12],
                 [13,14,15]])

output y should be array([[ 3.97,  2.  ,  3.  ],
   [ 4.  ,  5.  ,  2.  ],
   [ 8.91,  8.  ,  9.  ],
   [10.  , 14.88, 12.  ],
   [13.  ,  2.  , 15.  ]])

编辑

所以我认为我将一些可行的东西组合在一起,使用稀疏矩阵作为掩码等......但考虑到所需的步骤数,这似乎可能不是特别高效。有没有更有效的方法来实现同样的目标?代码如下

    q_max_adjustments = np.multiply(gamma * Q1.max(1), 1-done)
    true_adjustments = R + q_max_adjustments
    mask = np.full((num_rows, num_cols), False)
    mask[np.arange(num_rows), A] = True
    value_mask = np.multiply(np.vstack(true_adjustments), mask)
    np.copyto(Q, value_mask, where=mask)

最佳答案

您的矢量化解决方案具有所有正确的元素,但包含一些不必要的复杂性。使用高级索引的简化版本是:

>>> y = Q.astype(float)
>>> D, = np.where(1-done)
>>> y[np.arange(A.size), A] = R
>>> y[D, A[D]] += gamma * Q1[D].max(axis=1)
>>> y
array([[ 3.97,  2.  ,  3.  ],
       [ 4.  ,  5.  ,  2.  ],
       [ 8.91,  8.  ,  9.  ],
       [10.  , 14.88, 12.  ],
       [13.  ,  2.  , 15.  ]]

关于python - 使用 Numpy 向量化 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49331882/

相关文章:

python - setuptools build_ext 的行为与 distutils 不同吗?

Python sqlite3 select from 语句在获取时返回空列表

python - 分配给 for 循环值

python - 使用大型数组的 NumPy 的 3D 高斯有效总和

python - 将 numpy 数组转换为类别

python - 如何使用 OpenCV-Python 更改某个区域的色调

python - 比较 python 中元素顺序不同的两个列表

python - 在OpenCV Python中缩减ROI

python - np.where 多个逻辑语句 pandas

python - 用于科学 3D 绘图的 Mayavi 替代品