Eigen密集矩阵求解 2 - 求解最小二乘系统
生活随笔
收集整理的這篇文章主要介紹了
Eigen密集矩阵求解 2 - 求解最小二乘系统
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
簡介
本篇介紹如何使用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.06553450.511211 -0.562082 Here is the right hand side b: -0.9059110.3577290.358593 The least-squares solution is:0.46358 0.0429898QR分解法
在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=bAx = bAx=b ? ATAx=ATbA^TAx = A^TbATAx=ATb, 這里對矩陣A有要求,ATAA^TAATA結果為方陣,如果矩陣的條件比較病態,則計算可能會急劇變大,考慮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 A: -0.999984 -0.0826997-0.736924 0.06553450.511211 -0.562082 b: -0.9059110.3577290.358593 The solution using normal equations is:0.463581 0.0429899總結
以上是生活随笔為你收集整理的Eigen密集矩阵求解 2 - 求解最小二乘系统的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 魅族20将至 魅族或将更换新“LOGO”
- 下一篇: java信息管理系统总结_java实现科