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

217. 实现 ELU 及其导数

EasyActivations

重要性 像 ELU 及其变体这样的平滑激活函数可以避免在小型 MLP head 中出现 dead units。

ELU 在零以下是平滑的,因此负输入仍能保持微小的梯度。

编写 elu(x, alpha=1.0)。返回 (y, dy),其中当 x > 0 时 y = x,否则 y = alpha * (exp(x) - 1);dy 是导数:当 x > 0 时 dy = 1,否则 dy = alpha * exp(x)。

函数def elu(x, alpha=1.0)
Play with it

ELU and its alpha

For x < 0, ELU = α(e^x − 1), which levels off at −α. The slope curve shows the backward pass.

024-4-2024x
input
0.00
ELU
0
ReLU
0
slope of ELU
1
ELUReLUslope

示例 1

输入: elu([1, 0, -1])

输出: y [1, 0, -0.6321] and dy [1, 1, 0.3679]

示例 2

输入: x = [-2, 3], alpha = 2.0

输出: ([-1.729329, 3.0], [0.270671, 1.0])

示例 3

输入: x = [50.0, -50.0]

输出: ([50.0, -1.0], [1.0, 1.92875e-22])

约束条件

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

对两个输出都对 x > 0 使用 np.where。在 x = 0 时使用负值分支。

提示 2

使用 np.where(x > 0, ...)。

提示 3

在 exp 内部对 x 在 0 处进行 clip,以防止较大的正值导致溢出。

常见错误
  • 对较大的正 x 调用 exp,导致溢出。
  • 在负值部分返回了 y 而不是导数。
理解思路

ELU 对正输入表现得像 identity 函数,但对于负输入,它会平滑地向下弯曲至 -alpha,而不是像 ReLU 那样直接截断为零。这使得负值仍能保持微小的梯度,并将平均激活值推向接近零的状态。Worked example with alpha = 1: 在 x = 2 时,y = 2 且 dy = 1。在 x = -2 时,y = e^-2 - 1 = 0.1353 - 1 = -0.8647,且 dy = e^-2 = 0.1353。当 alpha = 0.5 且 x = -1 时,y = 0.5 * (0.3679 - 1) = -0.316,且 dy = 0.5 * 0.3679 = 0.184。

对于 x > 0,y = x 且 dy = 1。否则 y = alpha * (exp(x) - 1) 且 dy = alpha * exp(x)。注意 x = 0 属于第二个分支,此时 y 为 0 且 dy 等于 alpha。一个便捷的检查方法:在负值分支上 dy = y + alpha。导数本身并不等于激活值。应用场景:某些 CNN 和 VAE,以及作为自归一化网络中 SELU 的构建模块。
主题
Activations
相似题目
  • 实现 GPT 和 BERT 中的激活函数 GELUEasy
  • 在输入值较大时计算不溢出的 softplusEasy
  • 实现 hard swishEasy
  • 计算 dead ReLU 单元的比例Easy
所有 Activations 道题目
反馈
217 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def elu(x, alpha=1.0):
# your code here
pass
​

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

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