当我生成随机矩阵并将它们变成半正定矩阵时遇到问题。如果我们采用随机矩阵 Q,然后将其与其转置相乘,那么结果应该是半正定的(没有负特征值)但是当我打印一些随机特征值时,我发现我有负值。我的代码有问题吗?我还想将特征值的最大值保存到一个向量中。我的 Q 随机矩阵是整数,我看到的特征值是实数,复数部分始终为 0。但是我也收到警告。让我先给你看我的代码
#here i create a random torch with N matrices of n by n size
Q = torch.randint(0, 10, size=(N, n, n))
#here i initialize my vector for the max eigenvalues
max=np.zeros(N)
#here i create a loop where i multiply each Q matrix in my torch with its transpose
for i in range(0,N):
Q[i] = Q[i]*Q[i].t()
#here i find my eigenvalues and save the max into my vector max
val,vec=lg.eig(Q[i])
max[i]= np.amax(val)
我得到的警告是
ComplexWarning: Casting complex values to real discards the imaginary part
和我的特征值,我使用命令从控制台打印它们
lg.eig(Q[0])
However i see for example
(array([120.20198423+0.j, -1.93985888+0.j, 34.73787466+0.j])
Which has a negative value
最佳答案
您的示例是一个随机整数矩阵,但您的警告消息暗示 Q
包含复数值。
因此,为了创建半正定矩阵,您必须将 Q
乘以其共轭 转置 torch.conj(Q).t()
(这相当于实数的转置)。
此外,您正在使用 *
计算点积,对于矩阵乘法,请使用 @
、torch.mm
或 torch .matmul
.
关于python - 将随机矩阵变为半正定矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63915315/