Python: numpy.linalg.linalgerror: last 2 dimensions of the array must be square

Python: numpy.linalg.linalgerror: last 2 dimensions of the array must be square

我有一个矩阵可以给出类似的结果:

a = 
[[ 3.14333470e-02  3.11644303e-02  3.03622814e-02  2.90406252e-02
   2.72220757e-02  2.49377488e-02  2.22267299e-02  1.91354055e-02
   1.57166688e-02  1.20290155e-02  8.13554227e-03  4.10286765e-03
  -8.19802426e-09 -4.10288390e-03 -8.13555810e-03 -1.20290306e-02
  -1.57166830e-02 -1.91354185e-02 -2.22267415e-02 -2.49377588e-02
  -2.72220839e-02 -2.90406315e-02 -3.03622856e-02 -3.11644324e-02
  -3.14333470e-02]
 [ 0.00000000e+00  2.90117128e-03  5.75270270e-03  8.50580375e-03
   1.11133681e-02  1.35307796e-02  1.57166756e-02  1.76336548e-02
   1.92489172e-02  2.05348252e-02  2.14693765e-02  2.20365808e-02
   2.22267328e-02  2.20365792e-02  2.14693735e-02  2.05348208e-02
   1.92489114e-02  1.76336477e-02  1.57166674e-02  1.35307704e-02
   1.11133581e-02  8.50579304e-03  5.75269150e-03  2.90115979e-03
  -1.15937571e-08]
 [ 0.00000000e+00  2.90117128e-03  5.75270270e-03  8.50580375e-03
   1.11133681e-02  1.35307796e-02  1.57166756e-02  1.76336548e-02
   1.92489172e-02  2.05348252e-02  2.14693765e-02  2.20365808e-02
   2.22267328e-02  2.20365792e-02  2.14693735e-02  2.05348208e-02
   1.92489114e-02  1.76336477e-02  1.57166674e-02  1.35307704e-02
   1.11133581e-02  8.50579304e-03  5.75269150e-03  2.90115979e-03
  -1.15937571e-08]]

我想计算特征值和特征向量

w, v = numpy.linalg.eig(a) 

我该怎么做?

您的数组不是正方形,只需填充零列即可修复。

import numpy 

a = numpy.array(([1,7,3,9],[3,1,5,1],[4,2,6,3]))

# fill with zeros to get a square matrix
z = numpy.zeros((max(a.shape), max(a.shape)))
z[:a.shape[0],:a.shape[1]] = a
a = z
w, v = numpy.linalg.eig(a) 

print(w)

print(v)

输出:

[10.88979431 -2.23132083 -0.65847348  0.        ]
[[-0.55662903 -0.89297739 -0.8543584  -0.58834841]
 [-0.50308806  0.25253601 -0.0201359  -0.58834841]
 [-0.66111007  0.37258146  0.51929401  0.39223227]
 [ 0.          0.          0.          0.39223227]]

您不能直接计算矩阵的特征值,因为它不是方阵。为了找到特征值和特征向量,必须对矩阵进行对角化,这涉及在中间步骤进行矩阵求逆,only square matrices are invertible.

为了从非方矩阵中找到特征值,您可以计算奇异值分解(在 numpy 中:np.linalg.svd). You can then relate the singular values with the eigenvalues as explained here, or here。引用其中一个答案:

Definition: The singular values of a m×n matrix A are the positive square roots of the nonzero eigenvalues of the corresponding matrix A.T*A. The corresponding eigenvectors are called the singular vectors.