numpy的:n个向量的外积 [英] Numpy: outer product of n vectors

查看:967
本文介绍了numpy的:n个向量的外积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一些numpy的简单,我相信应该有这样做的一个简单的方法。

基本上,我有不同长度 N 载体列表。如果 V1 [I] I 次出现的第一个向量的条目,然后我想找到一个 N 维数组,A,这样

  A [I,J,K ...] = V1 [I] V2 [J] V3 [K] ...

我的问题是:


  1. 只需要两个的vector 的参数。


  2. einsum 需要像ABCD ...,这似乎是不必要的参数。


  3. 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:

  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)

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆