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

222. 编写永不溢出的 sigmoid 和 log-sigmoid

MediumActivations

sigmoid(x) = 1 / (1 + exp(-x)) 看起来无害,但当 x = -1000 时,exp(-x) 会溢出,且 log(sigmoid(x)) 会变成 log(0) = -inf。像 DPO 和 binary cross-entropy 这样的损失函数需要保持精确的 log-sigmoid。

编写 sigmoid_and_log(x),为数组 x 返回 (s, ls):s = sigmoid(x) 且 ls = log(sigmoid(x))。对于 x 在 [-1000, 1000] 范围内的任何值,两者都必须是有限且准确的。

函数def sigmoid_and_log(x)
Play with it

Sigmoid squashes, log-sigmoid stays finite

Drag along the curve. Far from 0 the sigmoid flattens to 0 or 1 while log-sigmoid keeps a straight slope, which is why the stable form matters.

-7.5-5-2.50-505x
input
0.00
sigmoid
0.5
log-sigmoid
-0.6931
slope of sigmoid
0.25
sigmoidlog-sigmoid

示例 1

输入: x = [-2.0, 0.0, 3.0]

输出: ([0.119203, 0.5, 0.952574], [-2.126928, -0.693147, -0.048587])

示例 2

输入: sigmoid_and_log([-1000.0, -50.0])[1]

输出: [-1000.0, -50.0]

示例 3

输入: x = [1000.0]

输出: ([1.0], [0.0])

约束条件

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

log sigmoid(x) = -log(1 + exp(-x)) = min(x, 0) - log1p(exp(-|x|))。

提示 2

通过 exp(ls) 计算 s。

理解思路

sigmoid 将任何数字压缩到 (0, 1) 之间,但教科书公式在极端情况下会失效:exp(1000) 会溢出,而 log(sigmoid(-1000)) 会变成 log(0) = -inf,尽管真实答案约为 -1000。解决方法是根据符号进行拆分,使得 exp 看到的数字始终小于或等于零。

Worked example

x = 0 得到 s = 0.5 且 log-sigmoid = -0.693。对于 x = -1000,使用 s = exp(x) / (1 + exp(x)),这是一个极小的有限数,且 log-sigmoid = x - log1p(exp(x)) = -1000 - log1p(约等于 0) = -1000。对于 x = 1000,s = 1 / (1 + exp(-1000)) = 1,且 log-sigmoid = -log1p(exp(-1000)),约为 0。一个简洁的

log_sigmoid(x) = min(x, 0) - log1p(exp(-|x|))。当参数很小时,log1p 是准确的。Binary cross-entropy、DPO 和 reward model 的损失函数都需要一个永不返回 -inf 的 log-sigmoid。
主题
Activations
相似题目
  • 返回 SiLU 及其用于 backward pass 的精确导数Medium
  • 实现 mish 及其梯度Medium
  • 实现 GPT 和 BERT 中的激活函数 GELUEasy
  • 在输入值较大时计算不溢出的 softplusEasy
所有 Activations 道题目
反馈
222 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def sigmoid_and_log(x):
# your code here
pass
​

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

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