在numpy中创建外部产品数组 [英] Create array of outer products in numpy
问题描述
我有一组长度为m的n个向量。例如, n = 3 , m = 2 :
I have an array of n vectors of length m. For example, with n = 3, m = 2:
x = array([[1, 2], [3, 4], [5,6]])
我想将每个向量的外积与自身相连,然后将它们连接成一个形状(n,m,m)的方形矩阵数组。所以对于上面的 x
,我会得到
I want to take the outer product of each vector with itself, then concatenate them into an array of square matrices of shape (n, m, m). So for the x
above I would get
array([[[ 1, 2],
[ 2, 4]],
[[ 9, 12],
[12, 16]],
[[25, 30],
[30, 36]]])
我可以使用进行
循环这样做
np.concatenate([np.outer(v, v) for v in x]).reshape(3, 2, 2)
是否有一个numpy表达式在没有Python for
循环的情况下执行此操作?
Is there a numpy expression that does this without the Python for
loop?
奖金问题:因为外部产品是对称的,我不需要 mxm 乘法运算来计算它们。我可以从numpy获得这种对称优化吗?
Bonus question: since the outer products are symmetric, I don't need to m x m multiplication operations to calculate them. Can I get this symmetry optimization from numpy?
推荐答案
也许使用 einsum
?
>>> x = np.array([[1, 2], [3, 4], [5,6]])
>>> np.einsum('ij...,i...->ij...',x,x)
array([[[ 1, 2],
[ 2, 4]],
[[ 9, 12],
[12, 16]],
[[25, 30],
[30, 36]]])
这篇关于在numpy中创建外部产品数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!