在我的损失函数中的某处,我对一个大小为64*64的复数矩阵求逆。尽管torch.tensor支持复数矩阵求逆,但无法在训练循环中计算梯度,因为我得到了这个错误:
RuntimeError: inverse不支持对具有复杂类型的输出进行自动区分。
有没有人有解决这个问题的办法?也许是一个自定义函数而不是torch.inverse?
发布于 2021-01-14 16:08:12
您可以使用复数矩阵的实数分量自己求逆。
首先是一些线性代数:
复数矩阵C可以写成两个实数矩阵A和B的和(j是-1的sqrt ):
C = A + jB 求C的逆矩阵基本上就是找两个实数矩阵x和y,使得
(A + jB)(x + jy) = I + j0这归结为求解实值方程组:

既然我们知道了如何将复数矩阵求逆简化为实数矩阵求逆,我们就可以使用pytorch的solve为我们进行求逆了。
def complex_inverse(C):
A = torch.real(C)
B = torch.imag(C)
# construct the left hand side of the system of equations
# side note: from pytorch 1.7.1 you can use vstack and hstack instead of cat
lhs = torch.cat([torch.cat([A, -B], dim=1), torch.cat([B, A], dim=1)], dim=0)
# construct the rhs of the system of equations
rhs = torch.cat([torch.eye(A.shape[0]).to(A), torch.zeros_like(A)],dim=0)
# solve the system of equations
raw, _ = torch.solve(rhs, lhs)
# write the solution as a single complex matrix
iC = raw[:C.shape[0], :] + 1j * raw[C.shape[0]:, :]
return iC 您可以使用numpy验证解决方案:
# C is a complex torch tensor
iC = complex_inverse(C)
with torch.no_grad():
print(np.isclose(iC.cpu().numpy() @ C.cpu().numpy(), np.eye(C.shape[0])).all()) 请注意,通过使用块矩阵的求逆技巧,您可以减少solve操作的计算成本。
发布于 2021-06-22 00:04:17
从1.9开始,PyTorch现在支持复杂的自动评分。
https://stackoverflow.com/questions/65712154
复制相似问题