numpy的:n个向量的外积 [英] Numpy: outer product of n vectors
问题描述
我试图做一些numpy的简单,我相信应该有这样做的一个简单的方法。
基本上,我有不同长度 N
载体列表。如果 V1 [I]
是 I
次出现的第一个向量的条目,然后我想找到一个 N
维数组,A,这样
A [I,J,K ...] = V1 [I] V2 [J] V3 [K] ...
我的问题是:
-
外
只需要两个的vector 的参数。 -
einsum
需要像ABCD ...,这似乎是不必要的参数。 -
KRON
需要什么似乎像相当复杂的整形,并只需要两个参数。
我想避免尽可能多的复杂性越好,以便避免引入的错误。所以preferably我想一个命令。
到目前为止,最好的我有一些了的是:
VS = [V1,V2,V3 ...]
形状=地图(LEN,VS) #指定每个矢量的方向
newshapes =诊断(阵列(形状)-1)+1
重塑= [x.reshape(Y)为X,Y拉链(VS,newshapes) #直接产品
A =减少(拉姆达A,B:A * B,重塑,1)
您使用以下用途一行code:
减少(np.multiply,np.ix _(* VS))
np.ix _()
将做外广播,你需要减少,但是你可以通过ufunc np.multiply
无lambda表达式。
下面是比较:
导入numpy的是NP
VS = [np.r_ [1,2,3.0],np.r_ [4,5.0],np.r_ [6,7,8.0]
形状=地图(LEN,VS) #指定每个矢量的方向
newshapes = np.diag(np.array(形状)-1)+1
重塑= [x.reshape(Y)为X,Y拉链(VS,newshapes)#直接产品
A =减少(拉姆达A,B:A * B,重塑,1)
B =减少(np.multiply,np.ix _(* VS))np.all(A == B)
该reuslt:
真
I'm trying to do something simple in numpy, and I'm sure there should be an easy way of doing it.
Basically, I have a list of n
vectors with various lengths. If v1[i]
is the i
'th entry of the first vector then I want to find a n
-dimensional array, A, such that
A[i,j,k...] = v1[i] v2[j] v3[k] ...
My problem is that:
outer
only takes two vector arguments.einsum
requires a parameter like "abcd..." which seems unnecessary.kron
requires what seems like rather complex reshaping, and takes only two arguments.
I'd like to avoid as much complexity as possible, so as to avoid introducing bugs. So preferably I would like a single command.
So far, the best I have some up with is:
vs = [v1, v2, v3 ...]
shape = map(len, vs)
# specify the orientation of each vector
newshapes = diag(array(shape)-1)+1
reshaped = [x.reshape(y) for x,y in zip(vs, newshapes)]
# direct product
A = reduce(lambda a,b: a*b, reshaped, 1)
You use use following one line code:
reduce(np.multiply, np.ix_(*vs))
np.ix_()
will do the outer broadcast, you need reduce, but you can pass the ufunc np.multiply
without lambda function.
Here is the comparing:
import numpy as np
vs = [np.r_[1,2,3.0],np.r_[4,5.0],np.r_[6,7,8.0]]
shape = map(len, vs)
# specify the orientation of each vector
newshapes = np.diag(np.array(shape)-1)+1
reshaped = [x.reshape(y) for x,y in zip(vs, newshapes)]
# direct product
A = reduce(lambda a,b: a*b, reshaped, 1)
B = reduce(np.multiply, np.ix_(*vs))
np.all(A==B)
The reuslt:
True
这篇关于numpy的:n个向量的外积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!