線形回帰モデルを使う
線形回帰モデルを使うためにimportします。
from sklearn import linear_model
モデルを作成し、学習データを渡し、予測します。
予測時に学習データをの行列にしておく必要があります。
# 線形回帰のモデルを作成 model = linear_model.LinearRegression() # 学習 model.fit(x, y) # 予測直線表示のためのxを作成 予測するために行列にする(reshape) x2 = np.arange(-2, 2, 0.1).reshape(-1,1) y2 = model.predict(x2)
決定係数
回帰の場合結果の妥当性を客観的に評価する指標として決定係数が知られています。
一般に決定係数と呼ばれるものはいくつかありますが、今回紹介する決定係数は、以下で定義されます。
観測値と予測値が真の値に近ければ、分子が近づき、決定係数はに近くなります。
決定係数の値がに近いほど、その予測モデルは良いモデルとなります。
r2 = model.score(x, y) print('決定係数', r2)
ソース
import matplotlib.pyplot as plt import numpy as np from sklearn import linear_model # データの数 N = 10 # 乱数を固定 np.random.seed(1) # バラつきのある y = 3x -2 のデータを作成 x = np.linspace(0, 1, N).reshape(-1, 1) # 0 〜 1 までの乱数を 100 個つくる x = x * 4 - 2 # 値の範囲を -2 〜 2 に変更 y = 3 * x - 2 # y = 3x - 2 y += np.random.randn(N, 1) # 標準正規分布(平均 0, 標準偏差 1)の乱数を加える # 線形回帰のモデルを作成 model = linear_model.LinearRegression() # 学習 model.fit(x, y) # 予測直線表示のためのxを作成 予測するために行列にする(reshape) x2 = np.arange(-2, 2, 0.1).reshape(-1,1) y2 = model.predict(x2) # 係数、切片、決定係数を表示 print('係数', model.coef_) print('切片', model.intercept_) r2 = model.score(x, y) print('決定係数', r2) # グラフ表示 plt.scatter(x, y, marker ='+') plt.plot(x2, y2, color='orange') plt.show()
偉人の名言
小さなことからコツコツと。
西川きよし
動画
無し