104. 逐梯度步训练逻辑回归
逻辑回归预测 p = sigmoid(X @ w + b),并通过降低平均 log loss 进行训练。其梯度非常简单:预测误差乘以输入。
编写 logreg_step(X, y, w, b, lr) 函数,执行一次梯度下降步并返回 (new_w, new_b, loss),其中 loss 是步进前的平均 log loss。
grad_w = X.T @ (p - y) / n, grad_b = mean(p - y)。在 log 内部将 p clip 到 [1e-12, 1 - 1e-12] 范围内。
def logreg_step(X, y, w, b, lr)示例 1
输入: logreg_step([[1.0], [-1.0]], [1, 0], [0.0], 0.0, 0.5)
输出: ([0.25], 0.0, 0.6931)
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
提示 1
The gradient of the mean log loss is just the prediction error p - y times the inputs, averaged over the samples.
提示 2
Compute p = 1 / (1 + np.exp(-(X @ w + b))), the mean log loss, the gradients X.T @ (p - y) / n and mean(p - y), then step against them with lr.
提示 3
Clip p with np.clip(p, 1e-12, 1 - 1e-12) only inside the logs, use the unclipped p for the gradients, and remember the loss is measured before the update.
常见错误
- 有 Bug 的版本反转了 p - y 的符号,导致 loss 在上升。
理解思路
逻辑回归通过 sigmoid 将线性得分转换为概率,然后通过降低平均 log loss 进行学习。其梯度形式非常友好:预测误差 (p - y) 乘以输入。梯度下降通过沿着梯度的反方向移动权重,就像下山一样。
一个样本 x = [1], y = 1, w = [0], b = 0, lr = 0.1。得分为 0,所以 p = sigmoid(0) = 0.5。在更新前测得 Loss = -ln(0.5) = 0.693。误差 p - y = -0.5。grad_w = 1 x (-0.5) / 1 = -0.5 且 grad_b = -0.5。New w = 0 - 0.1 x (-0.5) = 0.05, new b = 0.05。在 log 内部将 p clip 到 [1e-12, 1 - 1e-12] 以防止出现 log(0)。
p = sigmoid(Xw + b); loss = -mean(y log p + (1 - y) log(1 - p)); grad_w = X^T (p - y) / n; grad_b = mean(p - y); 减去 lr 乘以每个梯度。点击欺诈模型仍在使用这种方法。
公司3
- Google the topic appears in interview reports Google Interview Prep (Deep-ML)
- Meta a candidate reported this question Timed ML screen: concept questions then classic models from scratch (Land the Lab)
- Microsoft the topic appears in interview reports Microsoft Interview Prep: Questions, Process & Study Plan
来自公开面试报告和指南。与这些公司无隶属关系或背书关系。