105. 使用 ridge regression 防止过拟合
当特征相关时,普通的 least squares 会产生巨大且不稳定的权重。Ridge 通过添加惩罚项 lam * ||w||^2 将权重拉向零。
编写 fit_ridge(X, y, lam) 并返回 (w, b)。首先对 X 和 y 进行中心化处理,使 bias 不受惩罚,求解 (Xc.T Xc + lam I) w = Xc.T yc,然后 b = mean(y) - mean(X) @ w。
def fit_ridge(X, y, lam)示例 1
输入: fit_ridge([[0.0], [1.0], [2.0]], [1.0, 3.0, 5.0], 1.0)
输出: ([1.3333], 1.6667)
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
中心化处理可以使 bias 不受惩罚。
提示 2
在中心化数据上求解出 w 后,再通过均值恢复 b。
常见错误
- 中心化可以使 bias 不受惩罚;错误的实现方式会对 bias 也进行惩罚,这会将预测值拉向零。
理解思路
Ridge regression 在 least squares 的基础上添加了惩罚项 lam x (sum of squared weights)。该惩罚项将权重拉向零,从而抑制了特征相关时产生的巨大且不稳定的权重。这就像添加了一个弹簧,除非数据有极强的拉力,否则会让每个权重都保持在零附近。首先对 X 和 y 进行中心化处理以避免截距受到惩罚,求解 w,然后通过均值恢复 b。Worked example, one feature: x = [0, 2], y = [1, 5]. Means 1 and 3, centred xc = [-1, 1], yc = [-2, 2]. xc^T xc = 2 and xc^T yc = 4. With lam = 0, w = 4 / 2 = 2. With lam = 2, w = 4 / (2 + 2) = 1, shrunk. Then b = 3 - 1 x 1 = 2.
w = solve(Xc^T Xc + lam I, Xc^T yc); b = mean(y) - mean(X) . w
Ridge 是一个标准的 baseline,其原理与神经网络中的 weight decay 相同。