はじめに
lmfitは非線形最小二乗法を用いてカーブフィットするためのライブラリであり、Scipy.optimize.curve_fitの拡張版に位置する。ここでは、フィッティングモデルの信頼区間を表示する方法について説明する。
コード
![](https://sabopy.com/wp/wp-content/uploads/2021/01/lmfit8_2_sig3-1.png)
解説
モジュールのインポートなど
バージョン
データの生成
np.random.randn(500)で標準正規分布に従うデータを500こ作成し、np.histgramでヒストグラムにすることで正規分布状のデータを得る。
図示すると以下のようになる。
![](https://sabopy.com/wp/wp-content/uploads/2021/01/lmfit8_1-1.png)
初期パラメータの作成
モデルには、定義済みのモデルであるGaussianModel()を用いる。model.guess(histo, x=bins)により、初期パラメータを推定できるのでそれをパラメータとして用いる。
カーブフィットと99%信頼区間
model.fit(histo, params, x=bins)でカーブフィットを行い、result.eval_uncertainty(sigma=3)で99%信頼区間を得る。
結果を図示すると以下のようになる。
![](https://sabopy.com/wp/wp-content/uploads/2021/01/lmfit8_2_sig3-1.png)
95%信頼区間
95%信頼区間はresult.eval_uncertainty(sigma=2)で得ることができて、下のようになる。
![](https://sabopy.com/wp/wp-content/uploads/2021/01/lmfit8_2_sig2-1.png)
68%信頼区間
68%信頼区間はresult.eval_uncertainty(sigma=1)で得られ、下のようになる。
![](https://sabopy.com/wp/wp-content/uploads/2021/01/lmfit8_2_sig1-1.png)
subplotsで68–95–99%の信頼区間を並べて表示
![](https://sabopy.com/wp/wp-content/uploads/2021/01/lmfit8_3-1-800x400.png)
参考
Non-Linear Least-Squares Minimization and Curve-Fitting for Python — Non-Linear Least-Squares Minimization and Curve-Fitting for Python
doc_model_uncertainty.py — Non-Linear Least-Squares Minimization and Curve-Fitting for Python
コメント