Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

python - Numpy: outer product of n vectors

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:

  1. outer only takes two vector arguments.

  2. einsum requires a parameter like "abcd..." which seems unnecessary.

  3. 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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...