Machine-learning-with-python-multiple-linear-regression

提供:Dev Guides
移動先:案内検索

ML-多重線形回帰

2つ以上の機能を使用して応答を予測するのは、単純な線形回帰の拡張です。 数学的には、次のように説明できます-

*n* の観測値、 *p* の特徴を持つデータセットを考えます。 1つの応答としての独立変数と *y* 従属変数p個の特徴の回帰直線は次のように計算できます-

h(x _ \ {i})\:= \:b _ \ {0} \:+ \:b _ \ {1} x _ \ {i1} \:+ b _ \ {2} x _ \ {i2} \: + \ dotsm + b _ \ {p} x _ \ {ip}

ここで、$ h(x _ \ {i})$は予測応答値であり、$ b _ \ {0}、b _ \ {1}、b _ \ {2}、\ dotsm \:b _ \ {p} $は回帰です。係数。

多重線形回帰モデルには、常に計​​算を次のように変更する残留誤差として知られるデータの誤差が含まれます-

h(x _ \ {i})\:= \:b _ \ {0} + b _ \ {1} x _ \ {i1} + b _ \ {2} x _ \ {i2} + \ dotsm + b _ \ {p } x _ \ {ip} + e _ \ {i}

また、次のように上記の方程式を書くことができます-

$ y _ \ {i} \:= \:h(x _ \ {i})+ e _ \ {i} \:or \:e _ \ {i} \:= \:y _ \ {i} -h(x_ \ {i})$

Pythonの実装

この例では、scikit Learnからボストンの住宅データセットを使用します-

まず、次のように必要なパッケージのインポートから始めます-

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model, metrics

次に、次のようにデータセットをロードします-

boston = datasets.load_boston(return_X_y = False)

次のスクリプト行は、特徴行列、Xと応答ベクトル、Yを定義します-

X = boston.data
y = boston.target

次に、次のようにデータセットをトレーニングセットとテストセットに分割します-

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.7, random_state = 1)

今、線形回帰オブジェクトを作成し、次のようにモデルを訓練します-

reg = linear_model.LinearRegression()
reg.fit(X_train, y_train)
print('Coefficients: \n', reg.coef_)
print('Variance score: {}'.format(reg.score(X_test, y_test)))
plt.style.use('fivethirtyeight')
plt.scatter(reg.predict(X_train), reg.predict(X_train) - y_train, color = "green", s = 10, label = 'Train data')
plt.scatter(reg.predict(X_test), reg.predict(X_test) - y_test, color = "blue", s = 10, label = 'Test data')
plt.hlines(y = 0, xmin = 0, xmax = 50, linewidth = 2)
plt.legend(loc = 'upper right')
plt.title("Residual errors")
plt.show()

出力

Coefficients:
[-1.16358797e-01 6.44549228e-02 1.65416147e-01 1.45101654e+00 -1.77862563e+01
   2.80392779e+00 4.61905315e-02 -1.13518865e+00 3.31725870e-01 -1.01196059e-02
   -9.94812678e-01 9.18522056e-03 -7.92395217e-01]
Variance score: 0.709454060230326

残留エラー