Tingiskhan - 7 months ago 57

Python Question

Assume that I have two arrays

`V`

`Q`

`V`

`(i, j, j)`

`Q`

`(j, j)`

`Q`

`V`

`(i, j, j)`

`i`

`import numpy as np`

v = np.random.normal(size=(100, 5, 5))

q = np.random.normal(size=(5, 5))

output = np.zeros_like(v)

for i in range(v.shape[0]):

output[i] = q.dot(v[i])

However, this is way too slow for my needs, and I'm guessing there is a way to vectorize this operation using either

`einsum`

`tensordot`

Answer

You can certainly use `np.tensordot`

, but need to swap axes afterwards, like so -

```
out = np.tensordot(v,q,axes=(1,1)).swapaxes(1,2)
```

With `np.einsum`

, it's a bit more straight-forward, like so -

```
out = np.einsum('ijk,lj->ilk',v,q)
```