LoginSignup
0
0

[Python] 回帰分析の実装 statsmodels.formula.api

Last updated at Posted at 2024-04-13

はじめに

パッケージstatsmodelsを用いて各種回帰分析を実装します。この記事では、R-ライクな構文で記述できるstatsmodels.formula.apiを用います。

公式ドキュメント
https://www.statsmodels.org/stable/
https://www.statsmodels.org/stable/example_formulas.html#fitting-models-using-r-style-formulas

コード

インポート

import pandas as pd
import numpy as np
import statsmodels.formula.api as smf

データの読み込み

df = pd.read_csv('./Data.csv', index_col=0)

回帰分析

代表的な回帰分析の実装コードを示しますが、どれも基本的な構文は同じです。
(formula='目的変数 ~ 説明変数1 + 説明変数2 + 説明変数3 + ....', data=df)

OLS

最小二乗法(Ordinary least squares)による回帰分析。

model = smf.ols(formula='BW ~ height + age + sex', data=df)
result = model.fit()

GLS

一般化最小二乗法(Generalized least squares)による回帰分析。

model = smf.gls(formula='BW ~ height + age + sex', data=df)
result = model.fit()

ロジスティック回帰

model = smf.logit(formula='BW ~ height + age + sex', data=df)
result = model.fit()

他にも様々な回帰が実装可能で、公式ドキュメントに書かれています。

結果の出力

決定係数や回帰係数を含むサマリーが出力されます。

result.summary()

回帰モデルによる予測

.predict()を用います。
下の例では、元データをそのままモデルに適用しています。

prediction = result.predict(df[['height', 'age', 'sex']])
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0