Machine-learning-with-python-simple-linear-regression
機械学習-単純な線形回帰
単一の機能を使用して応答を予測する線形回帰の最も基本的なバージョンです。 SLRの前提は、2つの変数が線形に関連していることです。
Pythonの実装
SLRをPythonに実装するには、2つの方法があります。1つは独自のデータセットを提供する方法、もう1つはscikit-learn pythonライブラリのデータセットを使用する方法です。
- 例1 *-次のPython実装例では、独自のデータセットを使用しています。
まず、次のように必要なパッケージのインポートから始めます-
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
次に、SLRの重要な値を計算する関数を定義します-
def coef_estimation(x, y):
次のスクリプト行は、観測数nを与えます-
n = np.size(x)
xとyベクトルの平均は次のように計算できます-
m_x, m_y = np.mean(x), np.mean(y)
次のようにxに関する交差偏差と偏差を見つけることができます-
SS_xy = np.sum(y*x) - n*m_y*m_x
SS_xx = np.sum(x*x) - n*m_x*m_x
次に、回帰係数、すなわち bは次のように計算することができます-
b_1 = SS_xy/SS_xx
b_0 = m_y - b_1*m_x
return(b_0, b_1)
次に、回帰直線をプロットし、応答ベクトルを予測する関数を定義する必要があります-
def plot_regression_line(x, y, b):
次のスクリプト行は、実際のポイントを散布図としてプロットします-
plt.scatter(x, y, color = "m", marker = "o", s = 30)
次のスクリプト行は、応答ベクトルを予測します-
y_pred = b[0] + b[1]*x
次のスクリプト行は回帰直線をプロットし、それらにラベルを付けます-
plt.plot(x, y_pred, color = "g")
plt.xlabel('x')
plt.ylabel('y')
plt.show()
最後に、データセットを提供し、上記で定義した関数を呼び出すためのmain()関数を定義する必要があります-
def main():
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y = np.array([100, 300, 350, 500, 750, 800, 850, 900, 1050, 1250])
b = coef_estimation(x, y)
print("Estimated coefficients:\nb_0 = {} \nb_1 = {}".format(b[0], b[1]))
plot_regression_line(x, y, b)
if __name__ == "__main__":
main()
出力
Estimated coefficients:
b_0 = 154.5454545454545
b_1 = 117.87878787878788
- 例2 *-次のPython実装例では、scikit-learnの糖尿病データセットを使用しています。
まず、次のように必要なパッケージのインポートから始めます-
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
次に、糖尿病データセットをロードし、そのオブジェクトを作成します-
diabetes = datasets.load_diabetes()
SLRを実装しているので、次のように1つの機能のみを使用します-
X = diabetes.data[:, np.newaxis, 2]
次に、次のようにデータをトレーニングセットとテストセットに分割する必要があります-
X_train = X[:-30]
X_test = X[-30:]
次に、次のようにターゲットをトレーニングセットとテストセットに分割する必要があります-
y_train = diabetes.target[:-30]
y_test = diabetes.target[-30:]
さて、モデルを訓練するには、次のように線形回帰オブジェクトを作成する必要があります-
regr = linear_model.LinearRegression()
次に、次のようにトレーニングセットを使用してモデルをトレーニングします-
regr.fit(X_train, y_train)
次に、次のようにテストセットを使用して予測を行います-
y_pred = regr.predict(X_test)
次に、MSE、分散スコアなどの係数を出力します。 次のように-
print('Coefficients: \n', regr.coef_)
print("Mean squared error: %.2f" % mean_squared_error(y_test, y_pred))
print('Variance score: %.2f' % r2_score(y_test, y_pred))
今、次のように出力をプロットします-
plt.scatter(X_test, y_test, color = 'blue')
plt.plot(X_test, y_pred, color = 'red', linewidth = 3)
plt.xticks(())
plt.yticks(())
plt.show()
出力
Coefficients:
[941.43097333]
Mean squared error: 3035.06
Variance score: 0.41