262. 仅对权重矩阵添加 L1 和 L2 惩罚及其梯度
重要性 在实际训练脚本的 weight decay 配置中,总是会排除 bias 和 normalization 参数。
正则化通常应用于权重而非 bias。一个简洁的辅助函数可以使这一规则显式化。
编写 regularize(params, l1, l2)。params 是一个从名称到数组的 dict。只有以 ".weight" 结尾的名称会被惩罚。返回 (penalty, grads),其中 penalty = sum over weights of l1 * sum(|w|) + 0.5 * l2 * sum(w^2)(float 类型),grads 是一个具有相同键的 dict:对于权重,梯度为 l1 * sign(w) + l2 * w(其中 sign(0) = 0);对于其他所有键,梯度为形状相同的全 0 数组。
def regularize(params, l1, l2)示例 1
输入: params = {"fc.weight": [1, -2], "fc.bias": [3]}, l1 = 0.1, l2 = 0.5
输出: penalty 1.55 and grads {"fc.weight": [0.6, -1.1], "fc.bias": [0]}
示例 2
输入: params = {'a.weight': [[0.0, 2.0], [-1.0, 0.0]], 'a.bias': [1.0, 1.0], 'norm.scale': [5.0]}, l1 = 0.2, l2 = 0.0
输出: (0.6, {'a.weight': [[0.0, 0.2], [-0.2, 0.0]], 'a.bias': [0.0, 0.0], 'norm.scale': [0.0]})
示例 3
输入: params = {'x.weight': [0.5, -0.5, 3.0]}, l1 = 0.0, l2 = 0.1
输出: (0.475, {'x.weight': [0.05, -0.05, 0.3]})
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
遍历 items;根据 name.endswith('.weight') 进行分支判断。
提示 2
np.sign 在 0 处返回 0,这通常是 subgradient。
提示 3
0.5 的系数使得 L2 的梯度正好是 l2 * w。
提示 4
对于跳过的键,返回 zeros_like。
常见错误
- 对 bias 进行了惩罚。
- 忘记了 0.5,导致梯度变成了 2 * l2 * w。
理解思路
惩罚项将权重拉向零,从而防止模型过度依赖任何单一特征。L1 以恒定的力进行拉动,因此较小的权重会被推向 0。L2 的拉动力与权重大小成正比,因此大权重缩减快,而小权重几乎不动。Bias 仅平移输出,因此惩罚它们并不能减少 overfitting。
w = [1, -2], l1 = 0.1, l2 = 0.5. L1 part 0.1 * 3 = 0.3. L2 part 0.5 * 0.5 * 5 = 1.25. Total 1.55. Gradient: 0.1 * [1, -1] + 0.5 * [1, -2] = [0.6, -1.1].
penalty = l1 * sum|w| + 0.5 * l2 * sum w^2, grad = l1 * sign(w) + l2 * w
ResNet 和 transformer 的训练方案仅对权重矩阵应用 weight decay,使用的正是这种名称过滤方式。
公司1
- Microsoft the topic appears in interview reports Microsoft Machine Learning Engineer Interview Questions | Screna AI
来自公开面试报告和指南。与这些公司无隶属关系或背书关系。