簡介
本篇介紹如何使用Eigen求解線性最小二乘系統。
一個系統可能無精確的解,比如Ax=b
的線性方程式,不存在解。這時,找到一個最接近的解x
,使得偏差Ax-b
儘可能地小,能夠滿足誤差要求error-margin
。那這個x
就稱爲最小二乘解。
這裏討論3個方法: SVD分解法,QR分解法,和規範等式。這中間,SVD分解法精度最高,但效率最差;規範式最快但精度最小;而QR分解法居中。
SVD分解法(Singular value decomposition)
使用Eigen中的BDCSVD類
的的solve()
方法,就能直接解出線性二乘系統了。但對奇異值計算,這樣並不足夠,你也會需要計算奇異向量。
示例如下,其使用了Matrix的bdcsvd()
方法來創建一個BDCSVD類的實例:
#include <iostream>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
int main()
{
MatrixXf A = MatrixXf::Random(3, 2);
cout << "Here is the matrix A:\n" << A << endl;
VectorXf b = VectorXf::Random(3);
cout << "Here is the right hand side b:\n" << b << endl;
cout << "The least-squares solution is:\n"
<< A.bdcSvd(ComputeThinU | ComputeThinV).solve(b) << endl;
}
執行:
$ g++ -I /usr/local/include/eigen3 matrix_svd1.cpp -o matrix_svd1
$
$ ./matrix_svd1
Here is the matrix A:
-0.999984 -0.0826997
-0.736924 0.0655345
0.511211 -0.562082
Here is the right hand side b:
-0.905911
0.357729
0.358593
The least-squares solution is:
0.46358
0.0429898
QR分解法
在Eigen中,QR分解類的solve()
方法用於計算最小二乘解。Eigen內提供了3中QR分解類:
- HouseholderQR: 無需行列轉換pivoting,速度快,但不穩定。
- ColPivHouseholderQR: 需要列轉換,稍慢,但精度高。
- FullPivHouseholderQR: 完全的行列轉換,所以最慢,但最穩定。
參考下面簡單示例,使用A.colPivHouseholderQr().solve(b)
:
MatrixXf A = MatrixXf::Random(3, 2);
VectorXf b = VectorXf::Random(3);
cout << "The solution using the QR decomposition is:\n"
<< A.colPivHouseholderQr().solve(b) << endl;
使用規範等式
有變換等式轉換: $ Ax = b ==> A^TAx = A^Tb A^TA$結果爲方陣,如果矩陣的條件比較病態,則計算可能會急劇變大,考慮MatrixXf(1000,2),需要計算一個1000X1000的矩陣了。
下面示例:
//matrix_decom_norm.cpp
#include <iostream>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
int main()
{
MatrixXf A = MatrixXf::Random(3, 2);
cout<<"A: "<<endl<<A<<endl;
VectorXf b = VectorXf::Random(3);
cout<<"b: "<<endl<<b<<endl;
cout << "The solution using normal equations is:\n"
<< (A.transpose() * A).ldlt().solve(A.transpose() * b) << endl;
}
執行:
$ g++ -I /usr/local/include/eigen3 matrix_decom_norm.cpp -o matrix_decom_norm
$ ./matrix_decom_norm
Here is the matrix A:
-0.999984 -0.0826997
-0.736924 0.0655345
0.511211 -0.562082
Here is the right hand side b:
-0.905911
0.357729
0.358593
The least-squares solution is:
0.46358
0.0429898