我想知道是否有一个内置操作可以将我的代码从 Python 循环中释放出来。
问题是这样的:我有两个矩阵 A
和 B
。 A
有 N
行,B
有 N
列。我想将 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/