正規化線性迴歸

Python 的降維

Jeroen Boeye

Head of Machine Learning, Faktion

線性模型概念

從特徵到目標

Python 的降維

建立自己的資料集

x1 x2 x3
1.76 -0.37 -0.60
0.40 -0.24 -1.12
0.98 1.10 0.77
... ... ...
Python 的降維

建立自己的資料集

x1 x2 x3
1.76 -0.37 -0.60
0.40 -0.24 -1.12
0.98 1.10 0.77
... ... ...

3 個特徵分佈

Python 的降維

建立自己的資料集

3 個特徵分佈

建立自己的目標特徵:

$y = 20 + 5x_1 + 2x_2 + 0x_3 + error$

Python 的降維

在 Python 中做線性迴歸

from sklearn.linear_model import LinearRegression

lr = LinearRegression()
lr.fit(X_train, y_train)

# Actual coefficients = [5 2 0]
print(lr.coef_)
[ 4.95  1.83 -0.05]
# Actual intercept = 20
print(lr.intercept_)
19.8
Python 的降維

在 Python 中做線性迴歸

# Calculates R-squared
print(lr.score(X_test, y_test))
0.976
Python 的降維

在 Python 中做線性迴歸

from sklearn.linear_model import LinearRegression

lr = LinearRegression()
lr.fit(X_train, y_train)

# Actual coefficients = [5 2 0]
print(lr.coef_)
[ 4.95  1.83 -0.05]
Python 的降維

損失函式:均方誤差

預測 vs. 實際

Python 的降維

損失函式:均方誤差

預測 vs. 實際(含 MSE)

Python 的降維

加入正規化

預測 vs. 實際(含 MSE + 公式)

Python 的降維

加入正規化

預測 vs. 實際(含 MSE + 公式 + 標註)

Python 的降維

加入正規化

預測 vs. 實際(含 MSE + 公式 + alpha)

Python 的降維

Lasso 迴歸器

from sklearn.linear_model import Lasso

la = Lasso()
la.fit(X_train, y_train)

# Actual coefficients = [5 2 0]
print(la.coef_)
[4.07 0.59 0.  ]
print(la.score(X_test, y_test))
0.861
Python 的降維

Lasso 迴歸器

from sklearn.linear_model import Lasso

la = Lasso(alpha=0.05)
la.fit(X_train, y_train)

# Actual coefficients = [5 2 0]
print(la.coef_)
[ 4.91  1.76 0.  ]
print(la.score(X_test, y_test))
0.974
Python 的降維

一起來練習吧!

Python 的降維

Preparing Video For Download...