torch.lu¶
- torch.lu(*args, **kwargs)¶
计算矩阵或矩阵批次的 LU 分解
A。返回一个包含A的 LU 分解和枢轴的元组。如果pivot设置为True,则执行枢轴操作。警告
torch.lu()已弃用,建议使用torch.linalg.lu_factor()和torch.linalg.lu_factor_ex()。torch.lu()将在未来的 PyTorch 版本中移除。LU, pivots, info = torch.lu(A, compute_pivots)应替换为LU, pivots = torch.linalg.lu_factor(A, compute_pivots)
LU, pivots, info = torch.lu(A, compute_pivots, get_infos=True)应替换为LU, pivots, info = torch.linalg.lu_factor_ex(A, compute_pivots)
注意
批次中每个矩阵的返回置换矩阵由大小为
min(A.shape[-2], A.shape[-1])的 1 索引向量表示。pivots[i] == j表示在算法的第i步中,第i行与第j-1行进行了置换。对于 CPU,无法使用
pivot=False的 LU 分解,尝试这样做会引发错误。但是,对于 CUDA,可以使用pivot=False的 LU 分解。如果
get_infos为True,则此函数不会检查分解是否成功,因为分解的状态存在于返回元组的第三个元素中。对于 CUDA 设备上大小小于或等于 32 的方形矩阵批次,由于 MAGMA 库中的错误(请参阅 magma 问题 13),会对奇异矩阵重复 LU 分解。
L、U和P可以使用torch.lu_unpack()推导出来。
警告
当
A为满秩矩阵时,此函数的梯度才是有限的。这是因为 LU 分解仅在满秩矩阵处可微。此外,如果A接近于非满秩,则梯度在数值上将不稳定,因为它依赖于 和 的计算。- 参数
- 返回值
包含以下内容的张量元组:
factorization (张量): 大小为 的分解结果
pivots (IntTensor): 大小为
, min ( m , n ) ) (*, \text{min}(m, n)) 的旋转点。pivots存储所有行的中间转置。最终排列perm可以通过对i = 0, ..., pivots.size(-1) - 1应用swap(perm[i], perm[pivots[i] - 1])来重建,其中perm最初是 个元素的恒等排列(本质上这就是torch.lu_unpack()的作用)。infos (IntTensor, 可选): 如果
get_infos为True,则这是一个大小为 的张量,其中非零值表示矩阵或每个小批次的分解是成功还是失败
- 返回类型
(张量, IntTensor, IntTensor (可选))
示例
>>> A = torch.randn(2, 3, 3) >>> A_LU, pivots = torch.lu(A) >>> A_LU tensor([[[ 1.3506, 2.5558, -0.0816], [ 0.1684, 1.1551, 0.1940], [ 0.1193, 0.6189, -0.5497]], [[ 0.4526, 1.2526, -0.3285], [-0.7988, 0.7175, -0.9701], [ 0.2634, -0.9255, -0.3459]]]) >>> pivots tensor([[ 3, 3, 3], [ 3, 3, 3]], dtype=torch.int32) >>> A_LU, pivots, info = torch.lu(A, get_infos=True) >>> if info.nonzero().size(0) == 0: ... print('LU factorization succeeded for all samples!') LU factorization succeeded for all samples!