python - NumPy 中可以使用分层广播吗?

标签 python arrays numpy array-broadcasting

我想知道是否有一个内置操作可以将我的代码从 Python 循环中释放出来。

问题是这样的:我有两个矩阵 ABAN 行,BN 列。我想将 A 中的每个 i 行与 B 中相应的 i 列相乘(使用 NumPy 广播)。生成的矩阵将在输出中形成 i 层。所以我的结果将是 3 维数组。

NumPy 中可以进行这样的操作吗?

最佳答案

直接表达您的要求的一种方法是使用 np.einsum() :

>>> A = np.arange(12).reshape(3, 4)
>>> B = np.arange(15).reshape(5, 3)
>>> np.einsum('...i,j...->...ij', A, B)
array([[[  0,   0,   0,   0,   0],
        [  0,   3,   6,   9,  12],
        [  0,   6,  12,  18,  24],
        [  0,   9,  18,  27,  36]],

       [[  4,  16,  28,  40,  52],
        [  5,  20,  35,  50,  65],
        [  6,  24,  42,  60,  78],
        [  7,  28,  49,  70,  91]],

       [[ 16,  40,  64,  88, 112],
        [ 18,  45,  72,  99, 126],
        [ 20,  50,  80, 110, 140],
        [ 22,  55,  88, 121, 154]]])

这使用 Einstein summation convention .

有关进一步讨论,请参阅 Vectors, Pure and Applied: A General Introduction to Linear Algebra 的第 3 章作者:T. W. Körner。在其中,作者引用了爱因斯坦写给 friend 的信中的一段有趣的段落:

"I have made a great discovery in mathematics; I have suppressed the summation sign every time that the summation must be made over an index which occurs twice..."

关于python - NumPy 中可以使用分层广播吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46024249/

相关文章:

python - 从 csv 文件创建 mne 数组

python - 根据模式重复数字 numpy

arrays - 面试测试——重新排列数组

java - 如何将 x 的值从小到大排列?

python - 根据两个 pandas DataFrame 之间的条件为新列分配值

python - numpy 和操作 a ,b = b, a

具有继承性的 Python 循环导入

python - 索引错误 : string index out of range while working with random module

python - 如何计算矩阵中每个单元格占列总和的比例?

pandas - 从不同组中减去值