2017-03-15 4 views

Antwort

5

Die outer method von NumPy ufuncs behandelt multidimensionalen Eingabe so, wie Sie wollen, so dass Sie

numpy.multiply.outer(a, b) 

tun konnte, anstatt numpy.outer.

Alle hier vorgeschlagenen Lösungen sind gleich schnell; für kleinen Arrays, hat multiply.outer einen leichten Vorsprung

enter image description here

-Code für das Bild zu erzeugen:

import numpy 
import perfplot 


def multiply_outer(data): 
    a, b = data 
    return numpy.multiply.outer(a, b) 


def outer_reshape(data): 
    a, b = data 
    return numpy.outer(a, b).reshape((a.shape + b.shape)) 


def tensor_dot(data): 
    a, b = data 
    return numpy.tensordot(a, b, 0) 


perfplot.show(
     setup=lambda n: (numpy.random.rand(n, n), numpy.random.rand(n, n)), 
     kernels=[multiply_outer, outer_reshape, tensor_dot], 
     n_range=[2**k for k in range(7)], 
     logx=True, 
     logy=True, 
     ) 
2

Ein Ansatz wäre np.outer und anschließend reshape -

np.outer(a,b).reshape((a.shape + b.shape)) 
1

np.einsum ist, was Sie suchen.

c[..., j] == a * b[j]

sollte

c = np.einsum('...i,j -> ...ij', a, b)

und c[..., i1, i2, i3] == a * b[i1, i2, i3] sollte

c = np.einsum('i,...jkl -> ...ijkl', a, b)

1

sein Ich glaube, Sie suchen Kroneker Produkt

zum Beispiel

> np.kron(np.eye(2), np.ones((2,2))) 

array([[ 1., 1., 0., 0.], 
     [ 1., 1., 0., 0.], 
     [ 0., 0., 1., 1.], 
     [ 0., 0., 1., 1.]]) 
2

Ich denke np.tensordot funktioniert auch

c = np.tensordot(a, b, 0) 

inds = np.reshape(np.indices(b.shape), (b.ndim, -1)) 
for ind in inds.T: 
    ind = tuple(ind) 
    assert np.allclose(a * b[ind], c[(...,) + ind]) 
else: 
    print('no error') 
# no error 
Verwandte Themen