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

109. 计算分位数 (pinball) loss

MediumRegression

重要性 Latency SLO 模型正是使用这种 loss 来预测每个请求的 p95 或 p99 时间。

若要预测第 90 百分位数而非平均值,请使用 pinball loss 进行训练。

为数组 y 和 yhat 以及范围在 (0, 1) 内的分位数 q 编写 pinball(y, yhat, q)。对于残差 r = y - yhat,若 r >= 0,loss 为 q * r,否则为 (q - 1) * r。返回所有元素的平均值,类型为 float。

函数def pinball(y, yhat, q)
Play with it

Pinball loss for quantile q

With r = y − ŷ, the loss is q · r for r ≥ 0 and (q − 1) · r otherwise. Move q to tilt the V and target a different quantile.

0123-3-2-10123residual r = y − ŷ
residual r = y − ŷ
0.00
pinball
0
absolute
0
slope of pinball
0.4
pinballabsolute

示例 1

输入: pinball([10, 10], [8, 12], 0.9)

输出: (0.9 * 2 + 0.1 * 2) / 2 = 1.0

示例 2

输入: y = [1, 2, 3, 4], yhat = [2, 2, 2, 2], q = 0.5

输出: 0.5

示例 3

输入: y = [5, 0, 3], yhat = [4, 1, 6], q = 0.1

输出: 1.233333

约束条件

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 4 tests to be accepted.
提示 1

np.maximum(q * r, (q - 1) * r) 可以同时覆盖两种情况。

提示 2

残差 r = y - yhat。

提示 3

两个分支都是线性的;取 q*r 和 (q-1)*r 中的较大值。

常见错误
  • 在负值分支写成 (1 - q) * r,这会导致 loss 变为负数。
  • 在计算残差时颠倒了 y 和 yhat,这会镜像分位数。
理解思路

Mean squared error 训练模型预测平均值。若要预测百分位数(例如延迟的第 90 百分位数),请使用 pinball loss。它会施加不等的惩罚:预测偏低每单位成本为 q,预测偏高每单位成本为 1 - q。当 q = 0.9 时,预测过低的价格是预测过高的九倍,因此最佳预测值会向第 90 百分位数移动。

Worked example

y = [5, 5, 5], yhat = [4, 5, 8], q = 0.8。残差 r = y - yhat = [1, 0, -3]。Losses: 0.8 * 1 = 0.8; 0.8 * 0 = 0; (0.8 - 1) * (-3) = 0.6。Mean = 1.4 / 3 = 0.4667。

当 r >= 0 时 loss_i = q * r,否则为 (q - 1) * r,结果始终为非负;返回平均值作为 float。在负值情况写成 (1 - q) * r 会导致 loss 为负,从而奖励预测过高的行为。该方法用于预测延迟百分位数、容量和需求范围,以及在分位数回归中用于预测区间。
主题
Regression
相似题目
  • 逐梯度步训练逻辑回归Medium
  • 使用 ridge regression 防止过拟合Medium
  • 使用 Huber loss 训练一个能够忽略离群值的回归模型Medium
  • 闭式解拟合加权最小二乘法Medium
所有 Regression 道题目
反馈
109 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def pinball(y, yhat, q):
# your code here
pass
​

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

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