如何找到矩阵的最大特征向量?

How to find the largest eigenvector of a matrix?

我正在尝试实现此功能但没有成功,我必须在不使用外部模块 numpy 等的情况下执行此操作。应用程序中有 3 个模块我正在编写此代码,Python 和 C#、C++ 但没有标准库以外的其他奇特库。

在一个单独的应用程序中,我使用了 numpy 的 svd,它工作得非常准确。所以我用它来匹配我的结果。我的方法是 PCA,到目前为止一切都很好。但是在我计算了我的对称协方差矩阵之后,我不知道如何找到最大的特征向量。

数据集始终是 3d 点,x、y 和 z。

vector center;
for(point p in points):
    center += p;
center /= points.count;

sumxx = 0;
sumxy = 0;
sumxz = 0;
sumyy = 0;
sumyz = 0;
sumzz = 0;
for(point p in points):
    vector s = p - center;
    sumxx += s.x * s.x;
    sumxy += s.x * s.y;
    sumxz += s.x * s.z;
    sumyy += s.y * s.y;
    sumyz += s.y * s.z;
    sumzz += s.z * s.z;

matrix3 mat = invert(matrix3(sumxx, sumxy, sumxz, sumxy, sumyy, sumyz, sumxz, sumyz, sumzz));
vector n;
if (determinant(mat) > 0)
    normal = find_largest_eigenvalue

让我们回顾一下您的问题,以澄清:

  1. 求矩阵的特征向量mat
  2. 这个特征向量应该与矩阵的最大特征值相关联
  3. 矩阵是principal component analysis的对称协方差矩阵。 特别是对称的
  4. 您的矩阵是 大小为 3 x 3 的正方形,如您的代码 matrix3 mat = ... 所示,并在(现已删除的)评论中得到确认。

在这些非常特殊的情况下,以下答案适用。然而,tmyklebu 警告这种方法对于某些病理矩阵的数值不稳定性,通常是当 r 接近 -1.


好的,让我们从 wikipedia's page on Characteristic polynomials

的一些阅读开始

In linear algebra, the characteristic polynomial of a square matrix is a polynomial, which is invariant under matrix similarity and has the eigenvalues as roots.

blah blah blah,让我们直接跳到3x3 matrix section in the page on Eigenvalue algorithms

If A is a 3×3 matrix, then its characteristic equation can be expressed as:

几行之后(或多或少)这个pseudo-code,for symmetric matrices(你说你有,如果我没记错的话- - 否则你可能有复杂的特征值):

p1 = A(1,2)^2 + A(1,3)^2 + A(2,3)^2
if (p1 == 0) 
   % A is diagonal.
   eig1 = A(1,1)
   eig2 = A(2,2)
   eig3 = A(3,3)
else
   q = (A(1,1) + A(2,2) + A(3,3)) / 3
   p2 = (A(1,1) - q)^2 + (A(2,2) - q)^2 + (A(3,3) - q)^2 + 2 * p1
   p = sqrt(p2 / 6)
   B = (1 / p) * (A - q * I)       % I is the identity matrix
   r = determinant(B) / 2

   % In exact arithmetic for a symmetric matrix  -1 <= r <= 1
   % but computation error can leave it slightly outside this range.
   if (r <= -1) 
      phi = pi / 3
   elseif (r >= 1)
      phi = 0
   else
      phi = acos(r) / 3
   end

   % the eigenvalues satisfy eig3 <= eig2 <= eig1
   eig1 = q + 2 * p * cos(phi)
   eig3 = q + 2 * p * cos(phi + (2*pi/3))
   eig2 = 3 * q - eig1 - eig3     % since trace(A) = eig1 + eig2 + eig3
end

所以在第一种情况下你想要max(eig1,eig2,eig3),在第二种情况下你想要eig1。让我们将这个最大的特征值称为e

对于特征向量,您现在只需求解 (A-e*I)x=0

查找特征值有不同的算法。有些工作从小到大,比如 QR;其他人从最大到最小工作,如幂迭代或 Jacobi-Davidson。

也许您需要切换算法。尝试强力法,看看是否有帮助。

https://scicomp.stackexchange.com/questions/1681/what-is-the-fastest-way-to-calculate-the-largest-eigenvalue-of-a-general-matrix