Pythonのstatsmodelsパッケージを使用して、順方向のステップワイズ回帰を実行します



Use Pythons Statsmodels Package Do Forward Stepwise Regression



Pythonのstatsmodelsには、いくつかのRスタイルの統計モデルとツールが含まれています。内部実装に関しては、statsmodelsはpatsyパッケージを使用してデータを行列に変換し、線形モデルを構築します。具体的な情報については、ペースト状のホームページhttp://patsy.readthedocs.io/en/latest/overview.htmlを参照してください。ただし、Pythonのstatsmodelsツールには順方向のステップワイズ回帰アルゴリズムはありません。ステップワイズ回帰の基本的な考え方は、変数を1つずつモデルに導入することです。各説明変数が導入された後、F検定が実行され、選択された説明変数が1つずつテストされます。その後の説明変数の導入により、最初に導入された説明変数が変更された場合重要でなくなった場合は、削除してください。新しい変数が導入されるたびに、有意な変数のみが回帰方程式に含まれるようにするため。これは、重要な説明変数が回帰方程式に選択されず、重要でない説明変数が回帰方程式から除外されなくなるまでの反復プロセスです。最終的な説明変数セットが最適であることを確認するには(https://baike.baidu.com/item/%E9%80%90%E6%AD%A5%E5%9B%9E%E5%BD%92/585832? fr =アラジン)。

誰かがインターネット上のstatsmodelsを使用して、ステップワイズ回帰のツールを作成しました。特定のWebサイトについては、https://planspace.org/20150423-forward_selection_with_statsmodels/を参照してください。試してみましたが、速度は悪くなく、sklearnで書いたものよりも優れています。具体的なコードは次のとおりです。



import statsmodels.formula.api as smf import pandas as pd def forward_selected(data, response): ''' Forward stepwise regression algorithm, the source code is from https://planspace.org/20150423-forward_selection_with_statsmodels/ Use Adjusted R-squared to judge whether the newly added parameters improve the statistical significance in the regression Linear model designed by forward selection. Parameters: ----------- data : pandas DataFrame with all possible predictors and response response: string, name of response column in data Returns: -------- model: an 'optimal' fitted statsmodels linear model with an intercept selected by forward selection evaluated by adjusted R-squared ''' remaining = set(data.columns) remaining.remove(response) selected = [] current_score, best_new_score = 0.0, 0.0 while remaining and current_score == best_new_score: scores_with_candidates = [] for candidate in remaining: formula = '{} ~ {} + 1'.format(response, ' + '.join(selected + [candidate])) score = smf.ols(formula, data).fit().rsquared_adj scores_with_candidates.append((score, candidate)) scores_with_candidates.sort() best_new_score, best_candidate = scores_with_candidates.pop() if current_score

せいぜい、この方法には欠点もあります。モデル内のパラメーターの増加に伴い、調整済み決定係数の増加は明らかではないため、後で追加された多くのパラメーターはモデルにほとんど影響を与えません。以下は、私自身のデータセット(98個のパラメーターを含む)で作成されたテストチャートです。パラメータ数が7を超える場合、パラメータを追加すると、モデルのR2を大幅に増やすことができないため、最終モデルが採用されます。最初の7つのパラメータで十分です。