データから予測する:重回帰分析
回帰分析
0:とは
定義:
1:ツール選択
参考まとめ:qiita.com
サンプルコード:
ーーーツール:statsmodels
StatsModels: Statistics in Python — statsmodels 0.6.1 documentation
ステップバイステップのわかりやすい解説:
Getting started — statsmodels 0.6.1 documentation
Fitting models using R-style formulas — statsmodels 0.6.1 documentation
ほか 例:
メモ:
この1行がないとエラー:
X = sm.add_constant(X)
エラー:
File "kaikibunseki_ex2.py", line 10, in <module>
y = np.dot(X, beta) + e
ValueError: shapes (100,2) and (3,) not aligned: 2 (dim 1) != 3 (dim 0)
この1行を使わなくてもいい:
import MySQLdb
import matplotlib.pyplot as plt
import statsmodels.api as sm
import pandas
import numpy as np
connection = MySQLdb.connect(host="localhost", db="agemono", user="root", passwd="password", charset="utf8")
cursor= connection.cursor()
#arrayをつくる
sales =
avg_max_temp =
avg_min_temp =
precipitation =
#データをそこに入れる
cursor.execute("select avg_sales, avg_min_temp, avg_max_temp, precipitation from minatoa")
data = cursor.fetchall()
for row in data:
sales.append(row[0])
avg_max_temp.append(row[1])
avg_min_temp.append(row[2])
precipitation.append(row[3])
#y=ax + b~ + c のとき、y,ax + b~ + cを定義。
y = sales
X = np.array([avg_max_temp, avg_min_temp, precipitation]).T ポイント1*
#.shapeにてマトリックスの (384, 10) x (384,) を確認。これにより、計算式として成り立つかを確認する。
print np.array(X).shape, np.array(y).shape
X = sm.add_constant(X)
# print '----------------------------------'
# print X
# print y
# print '----------------------------------'
mod = sm.OLS(y, X) # Describe model
res = mod.fit() # Fit model
print res.summary() # Summarize model
# show the intercept, etc
print res.params
ーーーーーーーーーーーーー
ポイント1*
.shapeでみたときに X, yが逆だった。このため、numpyのメソッド .Tを使って軸を反転。このためには numpyメソッドでarrayを作らないと認識されないので、np.array([-- , --, --]) とした。
-------------------------------------
結果:
OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.071
Model: OLS Adj. R-squared: 0.064
Method: Least Squares F-statistic: 9.674
Date: Tue, 18 Aug 2015 Prob (F-statistic): 3.62e-06
Time: 16:23:29 Log-Likelihood: -2441.3
No. Observations: 384 AIC: 4891.
Df Residuals: 380 BIC: 4906.
Df Model: 3
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [95.0% Conf. Int.]
------------------------------------------------------------------------------
const 845.7819 67.419 12.545 0.000 713.221 978.343
x1 37.7164 8.901 4.237 0.000 20.214 55.218
x2 -42.0506 9.224 -4.559 0.000 -60.188 -23.914
x3 0.0009 0.082 0.011 0.992 -0.160 0.161
==============================================================================
Omnibus: 120.607 Durbin-Watson: 0.960
Prob(Omnibus): 0.000 Jarque-Bera (JB): 1029.115
Skew: 1.066 Prob(JB): 3.39e-224
Kurtosis: 10.731 Cond. No. 853.
==============================================================================
予測値を出す
Prediction (out of sample) — statsmodels 0.6.0 documentation
ーーーーーーーーーーーーーーーーー
メモ: エラー:
TypeError: unsupported operand type(s) for /: 'list' and 'int'
行列の大きさをチェック!len()を使う。