Numpy:将矩阵平铺到更高的维度,但是具有比例

时间:2018-01-30 23:16:40

标签: python numpy

我需要在NumPy中实现以下行为:

public ClientAdapter (ArrayList<name>mylist,Context context){
this.mylist=mylist;
this.arraylist=mlist;  //use this as your acual list--> inside onBindViewHolder and getCount()
this.context=context;
 }

我可以使用a = [1, 2, 3] b = [[1, 0], [0, 1]] c = f(a, b) > c = [[[1, 0], [0, 1]], [[2, 0], [0, 2]], [[3, 0], [0, 3]]] 实现此功能,但这不明显,需要注释才能使代码的意图清晰。是否有任何内置函数可以提供此行为?

3 个答案:

答案 0 :(得分:4)

NumPy ufuncs上的outer methodnumpy.outer更方便地处理非1D输入:

In [1]: import numpy
In [2]: a = [1, 2, 3]
In [3]: b = [[1, 0],
   ...:      [0, 1]]
In [4]: numpy.multiply.outer(a, b)
Out[4]: 
array([[[1, 0],
        [0, 1]],
       [[2, 0],
        [0, 2]],
       [[3, 0],
        [0, 3]]])

答案 1 :(得分:3)

在精神上,这就像outer,但我认为符号更清晰(至少对于numpy用户体验):

In [366]: a = np.arange(1,4); b=np.eye(2)
In [367]: c = a[:,None,None]*b[None,:,:]
In [368]: c
Out[368]: 
array([[[1., 0.],
        [0., 1.]],

       [[2., 0.],
        [0., 2.]],

       [[3., 0.],
        [0., 3.]]])

可能更漂亮:

In [375]: np.einsum('i,jk->ijk',a,b)
Out[375]: 
array([[[1., 0.],
        [0., 1.]],

       [[2., 0.],
        [0., 2.]],

       [[3., 0.],
        [0., 3.]]])

答案 2 :(得分:3)

最接近内置可能是np.einsum

>>> np.einsum('i,jk',a,b)
array([[[1, 0],
        [0, 1]],

       [[2, 0],
        [0, 2]],

       [[3, 0],
        [0, 3]]])

或者np.tensordot

>>> np.tensordot(a, b, ((),()))
array([[[1, 0],
        [0, 1]],

       [[2, 0],
        [0, 2]],

       [[3, 0],
        [0, 3]]])