numpy - how do i do vector multiplication in batch with python -


for example, have vector of shape[1,d]

if d = 4

v = np.array([[1, 2, 3, 4]]) # shape = [1,4] 

and do

np.dot(v.t,v) 

the result be

out[80]:  array([[ 1,  2,  3,  4],        [ 2,  4,  6,  8],        [ 3,  6,  9, 12],        [ 4,  8, 12, 16]]) 

now have lots of vectors, , in shape of [n,d]

that's n vectors d dimensions

how can result in efficient way

ps: result numpy.ndarray of shape [n,d,d]

in [758]: v = np.array([[1, 2, 3, 4]]) in [759]: v2 = np.vstack([v,v]) in [760]: v2.shape out[760]: (2, 4) in [761]: v2[:,none,:]*v2[:,:,none] out[761]:  array([[[ 1,  2,  3,  4],         [ 2,  4,  6,  8],         [ 3,  6,  9, 12],         [ 4,  8, 12, 16]],         [[ 1,  2,  3,  4],         [ 2,  4,  6,  8],         [ 3,  6,  9, 12],         [ 4,  8, 12, 16]]]) in [762]: _.shape out[762]: (2, 4, 4) 

i'm using broadcasting construct outer product.

checking against comment example

in [763]: x2= np.array([[1, 2], [1, 2]]) in [764]: x2[:,none,:]*x2[:,:,none] out[764]:  array([[[1, 2],         [2, 4]],         [[1, 2],         [2, 4]]]) 

you wanted:

in [765]: np.array([[[1, 2], [2, 4]],[[4, 2],[2, 1]]]) out[765]:  array([[[1, 2],         [2, 4]],         [[4, 2],         [2, 1]]]) 

the numbers there, 2nd plane flipped. want? evidently there's ambiguity in how dimensions map. if want, explain how you'd iteratively.


with einsum outer product is

in [770]: np.einsum('ij,ik->ijk', x2,x2) out[770]:  array([[[1, 2],         [2, 4]],         [[1, 2],         [2, 4]]]) 

with matmul expression is: v2[:,:,none]@v2[:,none,:].


Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -