正则化(Regularization) 是机器学习中对原始损失函数引入额外信息,以便防止过拟合和提高模型泛化性能的一类方法的统称。也就是目标函数变成了原始损失函数+额外项
常用的正则化一般有两种L1正则化和L2正则化
L1正则化的一般表达式:
a
r
g
m
i
n
[
J
(
w
)
+
α
∣
∣
w
∣
∣
1
]
argmin[J(w)+\alpha||w||_1]
argmin[J(w)+α∣∣w∣∣1?]
L2正则化的一般表达式:
a r g m i n [ J ( w ) + α ∣ ∣ w ∣ ∣ 2 2 ] argmin[J(w)+\alpha ||w||_2^2] argmin[J(w)+α∣∣w∣∣22?]
下面通过机器学习中三个典型模型说明正则化的作用,这一部分参考sklearn的用户手册, 里面会有更细节的说明
对于 y ^ ( w , x ) = w 0 + w 1 x 1 + . . . + w p x p \hat y(w, x)=w_0+w_1x_1+...+w_px_p y^?(w,x)=w0?+w1?x1?+...+wp?xp?这样的线性回归, 我们可以用OLS拟合出其系数 w 1 ? w p w_1-w_p w1??wp?和偏差 w 0 w_0 w0?
其基本的思想为:方程两边残余平方差最小
m
i
n
∣
∣
X
w
?
y
∣
∣
2
2
min||Xw-y||^2_2
min∣∣Xw?y∣∣22?
m i n ∣ ∣ X w ? y ∣ ∣ 2 2 + α ∣ ∣ w ∣ ∣ 2 2 min||Xw-y||^2_2+\alpha||w||^2_2 min∣∣Xw?y∣∣22?+α∣∣w∣∣22?
下面通过sklearn用户教程中的一个例子说明岭回归作为正则化函数的作用(更详细的可以参考)
This example also shows the usefulness of applying Ridge regression to highly ill-conditioned matrices. For such matrices, a slight change in the target variable can cause huge variances in the calculated weights. In such cases, it is useful to set a certain regularization (alpha) to reduce this variation (noise).
这个例子也展示岭回归在高度病态矩阵上的应用
# Author: Fabian Pedregosa -- <fabian.pedregosa@inria.fr>
# License: BSD 3 clause
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
# X is the 10x10 Hilbert matrix 10个样本10个特征
# 希尔伯特矩阵是一种数学变换矩阵,正定,且高度病态(即,任何一个元素发生一点变动,整个矩阵的行列式的值和逆矩阵都会发生巨大变化),病态程度和阶数相关。
X = 1.0 / (np.arange(1, 11) + np.arange(0, 10)[:, np.newaxis])
y = np.ones(10)
print(np.linalg.det(X))
Output:
2.1644528904064253e-53
可以看到矩阵X是一个高度病态的矩阵
n_alphas = 200
alphas = np.logspace(-10, -2, n_alphas)
coefs = []
for a in alphas:
ridge = linear_model.Ridge(alpha=a, fit_intercept=False)
ridge.fit(X, y)
coefs.append(ridge.coef_)
ax = plt.gca()
ax.plot(alphas, coefs)
ax.set_xscale("log")
ax.set_xlim(ax.get_xlim()[::-1]) # reverse axis
plt.xlabel("alpha")
plt.ylabel("weights")
plt.title("Ridge coefficients as a function of the regularization")
plt.axis("tight")
plt.show()
Output:
由于水平有限,做不出数学上的推导,在参考资料(L1、L2正则化)中有佬写了一些简单的数学证明
m i n 1 2 n s a m p l e s ∣ ∣ X w ? y ∣ ∣ 2 2 + α ∣ ∣ w ∣ ∣ 1 min\frac{1}{2n_{samples}}||Xw-y||^2_2+\alpha||w||_1 min2nsamples?1?∣∣Xw?y∣∣22?+α∣∣w∣∣1?
主要用于稀疏的场合…
看了很多模型大抵稀疏模型用L1正则化,L2正则化用于防止过拟合,一些模型中结合L1和L2正则化, 使其适用于更多场合
此外在sklearn官网还有一个例子具体体现了L2正则化的作用:
Common pitfalls in the interpretation of coefficients of linear models