【python tensorly 基本运算】

默认的后端就是为numpy,也可以设置为pytorch等
tl.set_backend('numpy')

1.1 创建张量

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]))

1.2 张量内积

在这里插入图片描述

print(tg.inner(a1, a2))

np.inner(A, B)计算的是A@B.T

1.3 多个向量外积

可以用

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

1.4 矩阵rao积

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))

1.5 矩阵kronecker积

print(tg.kronecker(mat_list))

1.6 张量和矩阵的n模积

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

1.7 Hadamard积

直接用乘号

1.8 tl.diag(v, k=0)

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]

1.9 张量展开与折叠

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))

a1本身
在这里插入图片描述
mode0展开
在这里插入图片描述

1.10 张量向量化

tl.tensor_to_vec(tensor)

1.11 向量张量化

tl.vec_to_tensor(vec, shape)

1.12 矩阵范数

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"))
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值