I have a 3D tensor T
of size (nrows, ncols, ncols)
, which I would like to multiply with a vector x
of size nrows
.
However, T
will be a huge sparse tensor with 6×6
nonzero entries in each row;
thus, it would be useful to store T
in a sparse format.
The most convenient way would be to define a Tsparse
tensor of size (nrows, 6, 6)
and a “pointer” matrix p
of size (nrows, 6)
which stores the indices of the nonzero entries for each row.
In this case, how can Tsparse and x multiplied in a Python code? If there were a direct way using NumPy
or SciPy
, I would highly prefer that option.
Anyway, here is my MWE, which needs to be rewritten based on what was stated above:
import numpy as np
nrows = 100
ncols = 20
p = np.zeros((nrows, 6), dtype=int)
for i in range(nrows):
p[i, :] = np.random.choice(np.arange(ncols), 6, replace=False)
T = np.zeros((nrows, ncols, ncols))
Tsparse = np.zeros((nrows, 6, 6))
for i in range(nrows):
for j in range(6):
for k in range(6):
entry = np.random.rand()
T[i, p[i, j], p[i, k]] = entry
Tsparse[i, j, k] = entry
x = np.array(np.random.rand(nrows))
res = np.tensordot(T, x, axes=([0], [0]))
print(res)
TobiR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.