Note
Go to the end to download the full example code.
Basic tensor operations
Example on how to use tensorly
to perform basic tensor operations.
import numpy as np
import tensorly as tl
from tensorly.testing import assert_array_equal
A tensor is simply a numpy array
tensor = tl.tensor(np.arange(24).reshape((3, 4, 2)))
print("* original tensor:\n{}".format(tensor))
* original tensor:
[[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]]
[[ 8 9]
[10 11]
[12 13]
[14 15]]
[[16 17]
[18 19]
[20 21]
[22 23]]]
Unfolding a tensor is easy
for mode in range(tensor.ndim):
print("* mode-{} unfolding:\n{}".format(mode, tl.unfold(tensor, mode)))
* mode-0 unfolding:
[[ 0 1 2 3 4 5 6 7]
[ 8 9 10 11 12 13 14 15]
[16 17 18 19 20 21 22 23]]
* mode-1 unfolding:
[[ 0 1 8 9 16 17]
[ 2 3 10 11 18 19]
[ 4 5 12 13 20 21]
[ 6 7 14 15 22 23]]
* mode-2 unfolding:
[[ 0 2 4 6 8 10 12 14 16 18 20 22]
[ 1 3 5 7 9 11 13 15 17 19 21 23]]
Re-folding the tensor is as easy:
for mode in range(tensor.ndim):
unfolding = tl.unfold(tensor, mode)
folded = tl.fold(unfolding, mode, tensor.shape)
assert_array_equal(folded, tensor)
Total running time of the script: (0 minutes 0.005 seconds)