向量本身的M乘积的外积 [英] Outer product of a vector with itself M-times
问题描述
我想根据长度为n的向量x创建一个M模式n维张量A,
I would like to create a M-mode, n-dimensional tensor A from a vector x of length n such that
A_[i_1, i_2, ... , i_M] = x[i_1] * x[i_2] * ... * x[i_M].
到目前为止,我的代码是
The code that I have so far is
A=np.multiply.outer(x,x)
for i in range(M-2):
A=np.multiply.outer(A,x)
我对使用Python进行编码还很陌生,所以我不确定是否有更紧凑/更方便的方法来计算此张量.
I'm rather new to coding in Python so I'm not sure if there is a more compact/convenient way of computing this tensor.
推荐答案
我们可以使用 np.multiply.reduce
来实现所有元素的按元素乘法的减少,就像这样-
We could make use of np.ix_
to create open grid versions of input array and then feed those to np.multiply.reduce
for element-wise multiplication reductions for all of those, like so -
A = np.multiply.reduce(np.ix_(*[x]*M))
扩展到其他支持的功能
我们可以将其扩展到其他具有reduce
方法的ufunc.因此,例如要执行外部addition
,它应该是-
We could extend this to other ufuncs that have the reduce
method. So, for example to perform outer addition
, it would be -
np.add.reduce(np.ix_(*[x]*M))
以此类推.
有关支持此功能的ufuncs
的完整列表,请参考 docs
.在Grep
-ing之后,我得到了以下支持reduce
方法的ufunc,因此可以利用早期发布的方法:
For a complete list of ufuncs
that support this feature, please refer to the docs
. After Grep
-ing for those, I got the following ufuncs that support reduce
method and hence could leverage the earlier posted approach :
加,减,乘,除,logaddexp,logaddexp2,true_divide, floor_divide,负数,正数,功率,余数,mod,fmod,divmod, 绝对,fabs,rint,符号,heaviside,conj,exp,exp2,log,log2, log10,expm1,log1p,sqrt,正方形,cbrt,倒数,gcd,lcm,sin, cos,tan,arcsin,arcos,arctan,arctan2,hypo,sinh,cosh,tanh, arcsinh,arccosh,arctanh,deg2rad,rad2deg,bitwise_and,bitwise_or, bitwise_xor,反转,left_shift,right_shift,更大,更大等于, less,less_equal,not_equal,equal,logical_and,logical_or, 逻辑异或,逻辑非,最大值,最小值,fmax,fmin,isfinite, isinf,isnan,isat,晶圆厂,signbit,copysign,nextafter,space, modf,ldexp,frexp,fmod,floor,ceil,trunc
add, subtract, multiply, divide, logaddexp, logaddexp2, true_divide, floor_divide, negative, positive, power, remainder, mod, fmod, divmod, absolute, fabs, rint, sign, heaviside, conj, exp, exp2, log, log2, log10, expm1, log1p, sqrt, square, cbrt, reciprocal, gcd, lcm, sin, cos, tan, arcsin, arccos, arctan, arctan2, hypot, sinh, cosh, tanh, arcsinh, arccosh, arctanh, deg2rad, rad2deg, bitwise_and, bitwise_or, bitwise_xor, invert, left_shift, right_shift, greater, greater_equal, less, less_equal, not_equal, equal, logical_and, logical_or, logical_xor, logical_not, maximum, minimum, fmax, fmin, isfinite, isinf, isnan, isnat, fabs, signbit, copysign, nextafter, spacing, modf, ldexp, frexp, fmod, floor, ceil, trunc
这篇关于向量本身的M乘积的外积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!