正则化线性回归

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 中的降维

损失函数:均方误差(MSE)

预测值 vs. 实际值

Python 中的降维

损失函数:均方误差(MSE)

预测值 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 中的降维

Passons à la pratique !

Python 中的降维

Preparing Video For Download...