默认的后端就是为numpy,也可以设置为pytorch等
tl.set_backend('numpy')
import numpy as np
import tensorly as tl
import tensorly.tenalg as tg
a1 = tl.tensor(np.arange(24).reshape((3, 4, 2)))
a2 = tl.tensor(np.arange(24, 48).reshape([3, 4, 2]))
即
print(tg.inner(a1, a2))
而np.inner(A, B)
计算的是[email protected]
可以用
a1 = np.array([1, 2, 3])
a2 = np.array([4, 5, 6, 7])
a3 = np.array([0, 4])
print(tg.outer((a1, a2, a3)))
也等同于
res = np.einsum('i,j,k->ijk',v1,v2,v3)
np.einsum可以参考这篇博客
https://blog.csdn.net/weixin_40937909/article/details/78474257
mat_list = [np.arange(6).reshape(-1, 2), np.arange(6, 10).reshape(-1, 2)]
# 其中mat_list是需要作rao积的矩阵list
print(tg.khatri_rao(mat_list))
print(tg.kronecker(mat_list))
a1 = tl.tensor(np.arange(12).reshape((3, 2, 2)))
matrix = np.arange(6).reshape(2, 3)
print(tg.mode_dot(a1, matrix, mode=0)) # 2x2x2的tensor
张量的维数使用
tl.ndim(a1) # or a1.ndim
直接用乘号
If v is a 2-D array, return a copy of its k-th diagonal. If v is a 1-D array, return a 2-D array with v on the k-th diagonal.
print(tl.diag(np.array([1, 2, 3]), k=4))
x = np.arange(9).reshape((3, 3))
print(tl.diag(x)) # [0 4 8]
a1 = tl.tensor(np.arange(12).reshape((3, 2, 2)))
unfold_0 = tl.unfold(a1, mode=0)
print(unfold_0)
# 折叠fold
print(tl.fold(unfold_0, mode=0, shape=a1.shape))
tl.tensor_to_vec(tensor)
tl.vec_to_tensor(vec, shape)
x = np.arange(9).reshape((3, 3))
print(tl.norm(x, order=1))
print(tl.norm(x, order=2))
print(tl.norm(x, order="inf"))
0范数
l0 = np.linalg.norm(x.flatten(), ord=0)
核范数
print(np.linalg.norm(x, ord="nuc"))