LoginSignup
1
3

More than 3 years have passed since last update.

Python Scikit-learn 線形回帰分析 非線形単回帰分析 機械学習

Posted at

Pythonでcsvデータを読み込んで線形回帰と非線形回帰を実施する方法について書きます。
windows10環境でPythonのverは3.7.3です.

コードは以下になります.

◆csvデータを読み込んで線形単回帰分析

import pandas as pd 
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

#変数
fig = plt.figure()
ax = fig.add_subplot(1,1,1)

#y軸csvデータ読み込み
data = pd.read_csv('cp.csv') 
y = np.array(data)#配列化
y = y.reshape(-1,)#次元変更(2から1次元)

#日付のx軸を作成
x = pd.date_range('2019-08-30 00:00:00', periods=16, freq='d')
x1=np.arange(16)
x2 = [[x1] for x1 in x1]

#線形単回帰
from sklearn import linear_model
clf = linear_model.LinearRegression()
clf.fit(x2,y) # 予測モデルを作成

print("回帰係数= ", clf.coef_)
print("切片= ", clf.intercept_)
print("決定係数= ", clf.score(x2,y))

#グラフ作成
ax.plot(x2,y,'b')
ax.plot(x2, clf.predict(x2),'k')

#グラフフォーマットの指定
plt.xlabel("Days elapsed")#横軸ラベル                    
plt.ylabel("plice")#縦軸ラベル
plt.grid(True)#目盛表示                 
plt.tight_layout()#全てのプロットをボックス内に

plt.show()

◆csvデータを読み込んで非線形単回帰分析

import pandas as pd 
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

#変数
fig = plt.figure()
ax = fig.add_subplot(1,1,1)

#y軸csvデータ読み込み
data = pd.read_csv('cp.csv') 
y = np.array(data)#配列化
y = y.reshape(-1,)#次元変更(2から1次元)

#日付のx軸を作成
x = pd.date_range('2019-08-30 00:00:00', periods=16, freq='d')

#非線形回帰次数
x1=np.arange(16)
fit = np.polyfit(x1,y,5)
y2 = np.poly1d(fit)(x1)

#決定係数
from sklearn.metrics import r2_score
print(r2_score(y,y2))

#予測
x_30 = np.poly1d(fit)(30)
print(x_30)


#グラフ作成
ax.plot(x,y,'bo')
ax.plot(x,y2,'--k')

#グラフフォーマットの指定
days = mdates.DayLocator() 
daysFmt = mdates.DateFormatter('%m-%d')
ax.xaxis.set_major_locator(days)
ax.xaxis.set_major_formatter(daysFmt)
plt.xlabel("date")#横軸ラベル                    
plt.ylabel("price")#縦軸ラベル
plt.grid(True)#目盛表示                 
plt.tight_layout()#全てのプロットをボックス内に

plt.show()

回帰分析の技術説明と各コードの詳細な解説はこちら(´・ω・`)☟☟☟
https://kgrneer.com/python-numpy-scikit-kaiki/

重回帰についても勉強中です。

1
3
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
1
3