tf.tensordot

Tensor contraction of a and b along specified axes and outer product.

Tensordot (also known as tensor contraction) sums the product of elements from a and b over the indices specified by axes.

This operation corresponds to numpy.tensordot(a, b, axes).

Example 1: When a and b are matrices (order 2), the case axes=1 is equivalent to matrix multiplication.

Example 2: When a and b are matrices (order 2), the case axes = [[1], [0]] is equivalent to matrix multiplication.

Example 3: When a and b are matrices (order 2), the case axes=0 gives the outer product, a tensor of order 4.

Example 4: Suppose that \(a_{ijk}\) and \(b_{lmn}\) represent two tensors of order 3. Then, contract(a, b, [[0], [2]]) is the order 4 tensor \(c_{jklm}\) whose entry corresponding to the indices \((j,k,l,m)\) is given by:

\( c_{jklm} = \sum_i a_{ijk} b_{lmi} \).

In general, order(c) = order(a) + order(b) - 2*len(axes[0]).

import numpy as np
import tensorflow as tf

a = np.arange(60).reshape(3,4,5)
b = np.arange(24).reshape(4,3,2)
c = tf.tensordot(a,b, axes=([1,0],[0,1]))
c

<tf.Tensor: shape=(5, 2), dtype=int64, numpy=
array([[4400, 4730],
    [4532, 4874],
    [4664, 5018],
    [4796, 5162],
    [4928, 5306]])>
</td>
</tr>

</table>


# Another example
d = tf.random.uniform((3,4,5))
e = tf.random.uniform((5,3,2))
f = tf.tensordot(d,e, axes=([2,0],[0,1]))
f

<tf.Tensor: shape=(4, 2), dtype=float32, numpy=
array([[4.8271146, 4.493    ],
     [5.8537536, 5.492961 ],
     [5.2579894, 5.2020206],
     [3.5817177, 4.2104754]], dtype=float32)>
     
    ```

  Args:
    a: `Tensor` of type `float32` or `float64`.
    b: `Tensor` with the same type as `a`.
    axes: Either a scalar `N`, or a list or an `int32` `Tensor` of shape [2, k].
      If axes is a scalar, sum over the last N axes of a and the first N axes of
      b in order. If axes is a list or `Tensor` the first and second row contain
      the set of unique integers specifying axes along which the contraction is
      computed, for `a` and `b`, respectively. The number of axes for `a` and
      `b` must be equal. If `axes=0`, computes the outer product between `a` and
      `b`.
    name: A name for the operation (optional).

  <!-- Tabular view -->
   <table class="responsive fixed orange">
  <colgroup><col width="214px"><col></colgroup>
  <tr><th colspan="2"><h2 class="add-link">Returns</h2></th></tr>
  <tr class="alt">
  <td colspan="2">
  A `Tensor` with the same type as `a`.
  </td>
  </tr>

  </table>



  <!-- Tabular view -->
   <table class="responsive fixed orange">
  <colgroup><col width="214px"><col></colgroup>
  <tr><th colspan="2"><h2 class="add-link">Raises</h2></th></tr>

  <tr>
  <td>
  `ValueError`<a id="ValueError"></a>
  </td>
  <td>
  If the shapes of `a`, `b`, and `axes` are incompatible.
  </td>
  </tr><tr>
  <td>
  `IndexError`<a id="IndexError"></a>
  </td>
  <td>
  If the values in axes exceed the rank of the corresponding
  tensor.
  </td>
  </tr>
  </table>