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

216. 在输入值较大时计算不溢出的 softplus

EasyActivations

Softplus 是 ReLU 的平滑版本。当网络必须输出正数(如方差或速率)时,就会用到它。教科书公式 log(1 + exp(z)) 一旦 z 超过约 710 就会溢出为 inf。

为 NumPy 数组(或列表)x 编写 softplus(x, beta=1.0)。返回一个形状相同的数组,满足
softplus(x) = log(1 + exp(beta * x)) / beta

对于极大的正数和极小的负数输入,它必须返回有限且准确的值。

函数def softplus(x, beta=1.0)
Play with it

Softplus, a smooth ReLU

Raise beta and softplus(x) = log(1 + e^(βx)) / β hugs ReLU more tightly.

024-4-2024x
input
0.00
softplus
0.6931
ReLU
0
slope of softplus
0.5
softplusReLU

示例 1

输入: softplus([0.0])

输出: [0.6931471805599453] (that is log 2). softplus([1000.0]) is [1000.0]

示例 2

输入: x = [-1.0, 0.0, 1.0]

输出: [0.313262, 0.693147, 1.313262]

示例 3

输入: x = [1000.0, -1000.0, 50.0]

输出: [1000.0, 0.0, 50.0]

约束条件

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

对于 z = beta * x,log(1 + exp(z)) 等于 max(z, 0) + log1p(exp(-|z|))。

提示 2

此时 exp 接收到的始终是非正数。

理解思路

Softplus 是平滑版的 ReLU:对于极小的负数输入,它接近 0;对于较大的正数输入,它接近输入本身。直接使用公式 log(1 + exp(z)) 在 z 超过约 710 时会失效,因为 exp 会溢出。解决方法是进行精确重写,确保永远不对正数取 exp。

Worked example

z = 3. 直接计算: log(1 + 20.0855) = 3.04859. 重写后: max(3, 0) + log(1 + exp(-3)) = 3 + 0.04859 = 3.04859,结果一致。若 beta = 2 且 x = 1.5,则 z = beta * x = 3,因此 softplus = 3.04859 / 2 = 1.52429。

softplus(x) = (max(z, 0) + log1p(exp(-|z|))) / beta, 其中 z = beta * x。当 exp(-|z|) 非常小时,log1p 能保持精度;对于 z = 1000,结果直接就是 1000。该函数用于必须为正数的输出,例如预测的方差、速率和 gate scales。
主题
Activations
相似题目
  • 实现 GPT 和 BERT 中的激活函数 GELUEasy
  • 实现 ELU 及其导数Easy
  • 实现 hard swishEasy
  • 计算 dead ReLU 单元的比例Easy
所有 Activations 道题目
反馈
216 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def softplus(x, beta=1.0):
# your code here
pass
​

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

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