torch.lu#
- torch.lu(*args, **kwargs)[source]#
计算矩阵或矩阵批次
A
的 LU 分解。如果设置了pivot
为True
,则返回 LU 分解和A
的主元。主元选择是在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 不支持主元选择为
False
的 LU 分解,尝试这样做会引发错误。但是,CUDA 支持主元选择为False
的 LU 分解。如果
get_infos
为True
,此函数不会检查分解是否成功,因为分解的状态包含在返回元组的第三个元素中。在 CUDA 设备上,对于尺寸小于或等于 32 的方阵批次,由于 MAGMA 库中的 bug(请参阅 magma issue 13),LU 分解会被重复执行。
可以使用
torch.lu_unpack()
从中导出L
、U
和P
。
警告
此函数在
A
是满秩时才会有有限的梯度。这是因为 LU 分解仅在满秩矩阵上可微。此外,如果A
接近于奇异矩阵(非满秩),由于计算 和 依赖于这些值,梯度会变得数值不稳定。- 参数
- 返回
包含以下元素的元组:
factorization (Tensor): 分解结果,形状为
pivots (IntTensor): 主元,形状为 。
pivots
存储了所有中间行交换。最终的置换perm
可以通过对于i = 0, ..., pivots.size(-1) - 1
应用swap(perm[i], perm[pivots[i] - 1])
来重构,其中perm
最初是 个元素的单位置换(这本质上是torch.lu_unpack()
所做的)。infos (IntTensor, optional): 如果
get_infos
为True
,则这是一个形状为 的张量,其中非零值表示矩阵或每个小批次的分解是否成功或失败。
- 返回类型
(Tensor, IntTensor, IntTensor (optional))
示例
>>> 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!