線性回歸(linear regression)的目標是找出一條直線,使得所有點到直線的距離(y 軸方向)之平方和為最小。我們可以使用 scikit-learn 的 linear_model.LinearRegression 來幫我們進行線性回歸,以下範例將會隨機的產生一些資料點來示範:

import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LinearRegression

x = np.linspace(0, 10, 1000)
y_raw = 3 * x + 2
y = y_raw + np.random.randn(1000)

model = LinearRegression()
model.fit(x[:, np.newaxis], y[:, np.newaxis])
print(model.coef_[0], model.intercept_)
y_fit = model.coef_[0] * x + model.intercept_

x2 = np.hstack([x[:, np.newaxis], np.ones((x.size, 1))])
(coef, intercept), _, _, _ = np.linalg.lstsq(x2, y, rcond=None)
print(coef, intercept)

plt.plot(x, y, '.', label='Random data')
plt.plot(x, y_raw, '-', label='Raw line')
plt.plot(x, y_fit, '-', label='Fitted line')
plt.legend()
plt.show()

在上述範例中:

如果要利用 LinearRegression 來擬合多項式,那麼你可以建立一個包含 x 的各個次方的矩陣,然後用該矩陣來對 y 做線性回歸。以下範例是一個擬合三次多項式的範例:

import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LinearRegression

x = np.linspace(-2, 2, 1000)
y_raw = x ** 3 - 2 * x ** 2 + 3 * x - 4
y = y_raw + np.random.randn(1000)

x2 = np.hstack([x[:, np.newaxis], x[:, np.newaxis] ** 2, x[:, np.newaxis] ** 3])
model = LinearRegression()
model.fit(x2, y[:, np.newaxis])
y_fit = model.predict(x2)

plt.plot(x, y, '.', label='Random data')
plt.plot(x, y_raw, '-', label='Raw line')
plt.plot(x, y_fit, '-', label='Fitted line')
plt.legend()
plt.show()