ライブラリインポート
from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt
:グラフ用データ作成
X、yをランダムで20個づつ生成
X = np.random.rand(20)
y = np.random.rand(20)
Xを昇順、sklearnに渡しやすい形にリシェイプ
X = np.sort(X).reshape(20,1)
X
中身は、こんなん。
>>array([[0.00460232],
[0.05499239],
[0.07249879],
[0.10357735],
[0.12304941],
[0.12399111],
[0.21219358],
[0.23241532],
[0.2975664 ],
[0.3241855 ],
[0.33018194],
[0.47777823],
[0.51792399],
[0.52408334],
[0.69196947],
[0.7926415 ],
[0.79900541],
[0.87883547],
[0.9491404 ],
[0.98766611]])
yも昇順
y = np.sort(y)
y
>>array([0.0042209 , 0.13057395, 0.16788022, 0.17403799, 0.25919865,
0.3030241 , 0.35839353, 0.39294163, 0.44227869, 0.46863275,
0.54436167, 0.55472105, 0.57756643, 0.60124576, 0.66758224,
0.69719244, 0.73952565, 0.81040396, 0.86517258, 0.95263727])
グラフ化
plt.scatter(X,y)
LinearRegression()でfit、表示。
model = LinearRegression()
model.fit(X,y)
plt.plot(X, model.predict(X))
plt.scatter(X,y)
こんな感じで表示できる。