Skip to content

Instantly share code, notes, and snippets.

@tagty
Last active March 15, 2020 13:06
Show Gist options
  • Save tagty/45a687456fd62a6d29f952120e2e2643 to your computer and use it in GitHub Desktop.
Save tagty/45a687456fd62a6d29f952120e2e2643 to your computer and use it in GitHub Desktop.
2群に分けられた目的変数に対して、1つ以上の説明変数の影響を調べるにはどうすればよいか?

2群に分けられた目的変数に対して、1つ以上の説明変数の影響を調べるにはどうすればよいか?

これを解析する手法として、ロジスティック回帰分析がある。
ロジスティック回帰分析をpythonで実行するにはどうすればよいか?

pandasでCSVを読み込み、statsmodelsのLogitを適用する

コードはgithubに公開する。
ロジスティック回帰分析は、2群に分けられた目的変数(従属変数)に対する,1つ以上の説明変数(独立変数)の影響を調べる統計解析の手法である。
今回はこのデータを用いる。
2群に分けられている objective に対して、 explanatory1explanatory2explanatory3 の影響を調べる。

pandasでCSVを読み込む

import pandas as pd

data = pd.read_csv('logistic_regression.csv', encoding='utf-8')
data.head()

statsmodelsを用いてロジスティック回帰分析を行う

statsmodelsLogit は第一引数に目的変数を第二引数に説明変数を入れる。

import statsmodels.api as sm

endog = data['objective']
exog = data[['explanatory1', 'explanatory2', 'explanatory3']]
logit = sm.Logit(endog, exog)
wrapper = logit.fit(disp=0)
print(wrapper.summary())

結果は以下のようになる。

                           Logit Regression Results                           
==============================================================================
Dep. Variable:              objective   No. Observations:                   20
Model:                          Logit   Df Residuals:                       17
Method:                           MLE   Df Model:                            2
Date:                Fri, 28 Feb 2020   Pseudo R-squ.:                  0.4447
Time:                        11:40:56   Log-Likelihood:                -7.4744
converged:                       True   LL-Null:                       -13.460
Covariance Type:            nonrobust   LLR p-value:                  0.002514
================================================================================
                   coef    std err          z      P>|z|      [0.025      0.975]
--------------------------------------------------------------------------------
explanatory1     3.4214      1.385      2.470      0.014       0.707       6.136
explanatory2    -1.4008      1.375     -1.019      0.308      -4.095       1.294
explanatory3    -0.3094      1.127     -0.275      0.784      -2.518       1.899
================================================================================

objectiveexplanatory1 に正の相関があることがわかる。

まとめ

今回は、2群に分けられた目的変数に対して、1つ以上の説明変数の影響を statsmodelsLogit を用いて調べた。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment