LoginSignup
7
10

More than 5 years have passed since last update.

PythonのNumpy、Pandas、scikit-learnモジュールでの回帰分析

Last updated at Posted at 2015-11-12

Pythonの勉強にいくつかのモジュールで回帰分析をおこなってみました。
参考にしたのは以下のサイト(統計学のサイトです)。

アイスクリーム統計学にようこそ!

データはリンク先から、CSVファイルに変換したものを使用しています。
(そのまま、テーブル読み込めよっていうツッコミはなしで)
scikit-learnモジュールの時、データ形に気がつくまで苦労しました。

Numpy モジュール の polyfit()メソッド

python2.7
#coding:utf-8
import numpy as np
import pandas as pd
dataframe = pd.read_csv('iceshop.csv')
x_data = dataframe['distance']
y_data = dataframe['custmer']

model = np.polyfit(x_data, y_data, 1)
m = np.poly1d(model)
print(m)

Pandas モジュール の ols()メソッド

python2.7
#coding:utf-8
import numpy as np
import pandas as pd
dataframe = pd.read_csv('iceshop.csv')
x_data = dataframe['distance']
y_data = dataframe['custmer']

model_ols = pd.ols(y=y_data, x=x_data, intercept = True)
print(model_ols)

scikit-learn モジュール の linear_model.LinearRegression() メソッド

python2.7
#coding:utf-8
import pandas as pd
from sklearn import linear_model

dataframe = pd.read_csv('iceshop.csv')
#dataframe型では動かないので注意
nparray = dataframe.as_matrix()
x_list = nparray[:,1]
y_list = nparray[:,2]

#1列にしないダメ
x_list2 = x_list.reshape(len(x_list),1)
y_list2 = y_list.reshape(len(y_list),1)

lm = linear_model.LinearRegression()
lm.fit(x_list2, y_list2)

print 'Coefficients :' + str(lm.coef_)
print 'Intercept :' + str(lm.intercept_)
print 'R2 :' + str(lm.score(x_list2, y_list2))

参考:データの取得して、CSVファイルで書き出す処理について

python2.7
#coding:utf-8
import pandas as pd

#アイスクリーム統計学の練習問題ページ
url = 'http://kogolab.chillout.jp/elearn/icecream/chap2/sec5.html'

fetched_dataframes = pd.io.html.read_html(url)
dataframe = fetched_dataframes[0]

#日本語の処理はめんどくさいのでヘッダー行を削除
dataframe.columns = ['shop_id','distance','custmer']
df2 = dataframe.drop([0])
df2.to_csv('iceshop.csv', index = False)     

以下のデータがCSVファイルで出力されます。

shop_id distance custmer
1 10 795
2 1200 213
3 500 465
4 50 694
5 740 403
6 30 782
7 10 769
8 360 561
9 150 692
10 930 361
11 620 385
12 65 723
7
10
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
7
10