python - numpy数组操作方法

标签 python numpy vectorization

>>> c= array([[[1, 2],
               [3, 4]],

               [[2, 1],
                [4, 3]],

               [[3, 2],
                [1, 4]]])
 >>> x
 array([[0, 1, 2],
       [3, 4, 5]])

返回一个矩阵,其中每一列都是 c 中每个矩阵与 x 的每个对应列乘以常规矩阵乘法的乘积。我正在尝试找出一种对其进行矢量化的方法,或者至少不使用 for 循环来解决它。

array([[6,  6, 16]
       12, 16, 22]])

为了进一步扩展这个操作,假设我有一个矩阵数组,比方说

>>> c
    array([[[1, 2],
    [3, 4]],

   [[2, 1],
    [4, 3]],

   [[3, 2],
    [1, 4]]])  
>>> x
    array([[[1, 2, 3],
    [1, 2, 3]],

   [[1, 0, 2],
    [1, 0, 2]],

   [[2, 3, 1],
    [0, 1, 0]]])


def fun(c,x):
    for i in range(len(x)):
         np.einsum('ijk,ki->ji',c,x[i])
         ##something

基本上,我想让 x 中的每个矩阵与 c 中的所有矩阵相乘。不引入这个for循环,返回一个类似于c的结构

我之所以这样做是因为我遇到了一个解决问题的问题,试图向量化

Xc(运算遵循普通矩阵列向量乘法),c为3维数组;就像上面的 c——一个列向量,每个元素都是一个矩阵(在 numpy 中是上面的形式)。 X 是每个元素都是一维数组的矩阵。 Xc 的输出应该是一维数组。

最佳答案

您可以使用 np.einsum -

np.einsum('ijk,ki->ji',c,x)

sample 运行-

In [155]: c
Out[155]: 
array([[[1, 2],
        [3, 4]],

       [[2, 1],
        [4, 3]],

       [[3, 2],
        [1, 4]]])

In [156]: x
Out[156]: 
array([[0, 1, 2],
       [3, 4, 5]])

In [157]: np.einsum('ijk,ki->ji',c,x)
Out[157]: 
array([[ 6,  6, 16],
       [12, 16, 22]])

对于 x 的 3D 情况,只需在 x 的字符串符号的开头附加新维度,并相应地在输出字符串符号处附加新维度,就像这样 -

np.einsum('ijk,lki->lji',c,x)

sample 运行-

In [151]: c
Out[151]: 
array([[[1, 2],
        [3, 4]],

       [[2, 1],
        [4, 3]],

       [[3, 2],
        [1, 4]]])

In [152]: x
Out[152]: 
array([[[1, 2, 3],
        [1, 2, 3]],

       [[1, 0, 2],
        [1, 0, 2]],

       [[2, 3, 1],
        [0, 1, 0]]])

In [153]: np.einsum('ijk,lki->lji',c,x)
Out[153]: 
array([[[ 3,  6, 15],
        [ 7, 14, 15]],

       [[ 3,  0, 10],
        [ 7,  0, 10]],

       [[ 2,  7,  3],
        [ 6, 15,  1]]])

关于python - numpy数组操作方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42317078/

相关文章:

python - Numpy append 不允许串联

python - 数据框中多列操作的矢量化解决方案

python - 转置 Pandas 数据框

python - 用于外键反向查找的django db_index

python - 导入 matplotlib 不起作用

python - 将点投影到由法线和点给出的平面上

python - NumPy bitwise_and 函数的简化

python - 二维矩阵 : Finding and deleting columns that are subsets of other columns

c# - 如何使用矢量 SSE 操作将图像像素数据的字节数组转换为灰度

python - 我可以将 IronPython 视为 C# 的 Pythonic 替代品吗?