how to 3-way outer product in numpy?

前端 未结 3 613
刺人心
刺人心 2021-01-21 07:42

About the numpy.outer [link] .

Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product will be M*N matrix.

3条回答
  •  盖世英雄少女心
    2021-01-21 08:20

    The direct way of doing this, taking full advantage of broadcasting is:

    a[:,None,None] * b[None,:,None] * c[None,None,:]
    

    np.ix_ does this reshaping for you, at a modest cost in speed

    In [919]: np.ix_(a,b,c)
    Out[919]: 
    (array([[[0]],
    
            [[1]],
    
            [[2]],
    
            [[3]],
    
            [[4]]]), array([[[10],
             [11],
             [12],
             [13]]]), array([[[20, 21, 22]]]))
    

    and the resulting arrays can be multiplied with

    np.prod(np.ix_(a,b,c))
    

    The einsum version is simple, and fast

    np.einsum('i,j,k',a,b,c)
    

    It's a good idea to learn all 3 methods.

    The problem with nesting outer is that expects the inputs to be 1d, or it flattens them. It can be used, but needs some reshaping

    np.outer(a,np.outer(b,c)).reshape(a.shape[0],b.shape[0],c.shape[0])
    

提交回复
热议问题