データ フレームがありpandas
、列 B と列 C の値から列 A の値を予測できるようにしたいと考えています。以下に簡単な例を示します。
import pandas as pd
df = pd.DataFrame({"A": [10,20,30,40,50],
"B": [20, 30, 10, 40, 50],
"C": [32, 234, 23, 23, 42523]})
理想的には、私は次のようなものを持っているのですols(A ~ B + C, data = df)
が、例アルゴリズム ライブラリから、scikit-learn
列ではなく行のリストを使用してモデルにデータを供給するようです。これを行うには、リスト内のリストにデータを再フォーマットする必要があり、そもそも pandas を使用する目的が達成されないようです。 pandas データ フレームのデータに対して OLS 回帰 (またはより一般的には任意の機械学習アルゴリズム) を実行する最も Python 的な方法は何ですか?
ベストアンサー1
理想的だと思っていたことをほぼ実現できると思います。統計モデルpandas
バージョン 0.20.0より前の「オプションの依存関係」の 1 つであったパッケージpandas
( でいくつかの用途に使用されていましたpandas.stats
。)
>>> import pandas as pd
>>> import statsmodels.formula.api as sm
>>> df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]})
>>> result = sm.ols(formula="A ~ B + C", data=df).fit()
>>> print(result.params)
Intercept 14.952480
B 0.401182
C 0.000352
dtype: float64
>>> print(result.summary())
OLS Regression Results
==============================================================================
Dep. Variable: A R-squared: 0.579
Model: OLS Adj. R-squared: 0.158
Method: Least Squares F-statistic: 1.375
Date: Thu, 14 Nov 2013 Prob (F-statistic): 0.421
Time: 20:04:30 Log-Likelihood: -18.178
No. Observations: 5 AIC: 42.36
Df Residuals: 2 BIC: 41.19
Df Model: 2
==============================================================================
coef std err t P>|t| [95.0% Conf. Int.]
------------------------------------------------------------------------------
Intercept 14.9525 17.764 0.842 0.489 -61.481 91.386
B 0.4012 0.650 0.617 0.600 -2.394 3.197
C 0.0004 0.001 0.650 0.583 -0.002 0.003
==============================================================================
Omnibus: nan Durbin-Watson: 1.061
Prob(Omnibus): nan Jarque-Bera (JB): 0.498
Skew: -0.123 Prob(JB): 0.780
Kurtosis: 1.474 Cond. No. 5.21e+04
==============================================================================
Warnings:
[1] The condition number is large, 5.21e+04. This might indicate that there are
strong multicollinearity or other numerical problems.