Dot product between 2D and 3D arrays
<p>Assume that I have two arrays <code>V</code> and <code>Q</code>, where <code>V</code> is <code>(i, j, j)</code> and <code>Q</code> is <code>(j, j)</code>. I now wish to compute the dot product of <code>Q</code> with each "row" of <code>V</code> and save the result as an <code>(i, j, j)</code> sized matrix. This is easily done using for-loops by simply iterating over <code>i</code> like</p>

<pre><code>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])
</code></pre>

<p>However, this is way too slow for my needs, and I'm guessing there is a way to vectorize this operation using either <code>einsum</code> or <code>tensordot</code>, but I haven't managed to figure it out. Could someone please point me in the right direction? Thanks</p>

<p>You can certainly use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.tensordot.html" rel="nofollow"><code>np.tensordot</code></a>, but need to swap axes afterwards, like so -</p>

<pre><code>out = np.tensordot(v,q,axes=(1,1)).swapaxes(1,2)
</code></pre>

<p>With <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a>, it's a bit more straight-forward, like so -</p>

<pre><code>out = np.einsum('ijk,lj-&gt;ilk',v,q)
</code></pre>

python numpy vectorization