Tensor dot product with rank one tensor from vector
I'm trying to compute an inner product between tensors in numpy.
I have a vector $x$ of shape (n,)
and a tensor $y$ of shape d*(n,)
with d 1
and would like to compute $\langle y, x^{\otimes d} \rangle$. That is, I want to compute the sum
$$\langle y, x^{\otimes d} \rangle= \sum_{i_1,\dots,i_d\in\{1,\dots,n\}}y[i_1, \dots, i_d]x[i_1]\dots x[i_d].$$
A working implementation I have uses a function to first compute $x^{\otimes d}$ and then uses np.tensordot
:
def d_fold_tensor_product(x, d) - np.ndarray:
Compute d-fold tensor product of a vector.
assert d 1, Tensor order must be bigger than 1.
xd = np.tensordot(x, x, axes=0)
for _ in range(d-2):
xd = np.tensordot(xd, x, axes=0)
return xd
n = 10
d = 4
x = np.random.random(n)
y = np.random.random(d * (n,))
result = np.tensordot(y, d_fold_tensor_product(x, d), axes=d)
Is there a more efficient and pythonic way? Perhaps without having to compute $x^{\otimes d}$.
Category Data Science