title: Python tensor product
body: <p>I have the following problem. For performance reasons I use <code>numpy.tensordot</code> and have thus my values stored in tensors and vectors.
  One of my calculations look like this:</p>
  <p><a href="https://i.stack.imgur.com/PLDSC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PLDSC.png" alt="enter image description here" /></a></p>
  <p><code>&lt;w_j&gt;</code> is the expectancy value of <code>w_j</code> and <code>&lt;sigma_i&gt;</code> the expectancy value of <code>sigma_i</code>. (Perhaps I should now have called is sigma, because it has nothing to do with standart deviation) Now for further calculations I also need the variance. To the get Variance I need to calculate:
  <a href="https://i.stack.imgur.com/KLmxY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KLmxY.png" alt="enter image description here" /></a></p>
  <p>Now when I implemented the first formula into python with <code>numpy.tensordot</code> I was really happy when it worked because this is quite abstract and I am not used to tensors. The code does look like this:</p>
  <pre><code>erc = numpy.tensordot(numpy.tensordot(re, ewp, axes=1), ewp, axes=1)
  </code></pre>
  <p>Now this works and my problem is to write down the correct form for the second formula. One of my attempts was:</p>
  <pre><code>serc = numpy.tensordot(numpy.tensordot(numpy.tensordot(numpy.tensordot
  (numpy.tensordot(re, re, axes=1), ewp, axes=1), ewp, axes=1)
  , ewp, axes=1), ewp, axes=1)
  </code></pre>
  <p>But this does give me a scalar instead of a vector. Another try was:</p>
  <pre><code>serc = numpy.einsum('m, m', numpy.einsum('lm, l -&gt; m',
  numpy.einsum('klm, k -&gt; lm', numpy.einsum('jklm, j -&gt; klm',
  numpy.einsum('ijk, ilm -&gt; jklm', re, re), ewp), ewp), ewp), ewp)
  </code></pre>
  <p>The vectors have lenght <code>l</code> and the dimension of the tensor is <code>l * l * l</code>. I hope my problem is understandable and thank you in advance!</p>
  <p>Edit: The first formula can in python also written down like: <code>erc2 = numpy.einsum('ik, k -&gt; i', numpy.einsum('ijk, k -&gt; ij', re, ewp), ewp)</code></p>