使用 scikit-learn 進行監督式學習
George Boorman
Core Curriculum Manager, DataCamp
$y = ax + b$
簡單線性迴歸使用單一特徵
$y$ = 目標
$x$ = 單一特徵
$a$, $b$ = 模型參數/係數:斜率、截距
如何選擇 $a$ 和 $b$?
為每條直線定義一個誤差函式
選擇讓誤差函式最小的那條線
誤差函式 = 損失函式 = 成本函式






$RSS = $ $\displaystyle\sum_{i=1}^{n}(y_i-\hat{y_i})^2$
普通最小平方法(OLS):使 RSS 最小化
$$ y = a_{1}x_{1} + a_{2}x_{2} + b$$
$$ y = a_{1}x_{1} + a_{2}x_{2} + a_{3}x_{3} +... + a_{n}x_{n}+ b$$
from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegressionX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)reg_all = LinearRegression()reg_all.fit(X_train, y_train)y_pred = reg_all.predict(X_test)
$R^2$:量化特徵可解釋的目標變異程度
高 $R^2$:


reg_all.score(X_test, y_test)
0.356302876407827
$MSE = $ $\displaystyle\frac{1}{n}\sum_{i=1}^{n}(y_i-\hat{y_i})^2$
$RMSE = $ $\sqrt{MSE}$
from sklearn.metrics import root_mean_squared_errorroot_mean_squared_error(y_test, y_pred)
24.028109426907236
使用 scikit-learn 進行監督式學習