BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Regression4 of 18 in topic

104. 逐梯度步训练逻辑回归

MediumRegression
提问于GoogleMetaMicrosoft

逻辑回归预测 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) 乘以输入。梯度下降通过沿着梯度的反方向移动权重,就像下山一样。

Worked example

一个样本 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 乘以每个梯度。点击欺诈模型仍在使用这种方法。
主题
Regression
公司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

来自公开面试报告和指南。与这些公司无隶属关系或背书关系。

相似题目
  • 使用 ridge regression 防止过拟合Medium
  • 使用 Huber loss 训练一个能够忽略离群值的回归模型Medium
  • 闭式解拟合加权最小二乘法Medium
  • 执行一次 softmax regression 的梯度下降步Medium
所有 Regression 道题目
反馈
104 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def logreg_step(X, y, w, b, lr):
# your code here
pass
​
logreg_step(_X, _y, np.zeros(2), 0.0, 0.5)[0]

此用例使用生成数据,因此按原样运行。按 + 添加你自己的用例。

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 4 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS