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

218. 实现 hard swish

EasyActivations

重要性 MobileNetV3 等端侧模型使用 hard swish,因为它不需要计算 exp。

移动端视觉模型使用一种廉价的分段线性版本来替代 swish。

编写 hard_swish(x)。返回 x * relu6(x + 3) / 6,其中 relu6(v) = min(max(v, 0), 6)。

函数def hard_swish(x)
Play with it

Hard swish next to SiLU

Hard swish = x · clip(x + 3, 0, 6) / 6 is a cheap piecewise copy of SiLU = x · σ(x).

024-4-2024x
input
0.00
hard swish
0
SiLU
0
slope of hard swish
0.5
hard swishSiLU

示例 1

输入: hard_swish([-4, 0, 1, 4])

输出: [0, 0, 0.6667, 4]

示例 2

输入: x = [-3, 3, 10]

输出: [-0.0, 3.0, 10.0]

示例 3

输入: x = np.linspace(-5, 5, 11)

输出: [-0.0, -0.0, -0.0, -0.333333, -0.333333, 0.0, 0.666667, 1.666667, 3.0, 4.0, 5.0]

约束条件

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

np.clip(x + 3, 0, 6)。

提示 2

门控部分是 clip(x + 3, 0, 6) / 6。

常见错误
  • 忘记了在 6 处的上限截断。
理解思路

Swish (x 乘以 sigmoid(x)) 效果很好,但 sigmoid 在手机上的计算成本很高。Hard swish 用一个分段线性门控替换了 sigmoid:在 -3 以下为 0,在 3 以上为 1,中间线性上升。它只需要几次加法、一次 clamp 和一次乘法。

Worked example

x = -3 得到 relu6(0) = 0,所以输出为 0。x = -1 得到 relu6(2) = 2,所以输出为 -1 * 2 / 6 = -0.333。x = 2 得到 relu6(5) = 5,所以输出为 2 * 5 / 6 = 1.667。x = 5 得到 relu6(8) = 6,所以输出为 5 * 6 / 6 = 5。

hard_swish(x) = x * relu6(x + 3) / 6,其中 relu6(v) = min(max(v, 0), 6)。在 6 处的截断使得当 x >= 3 时输出正好等于 x;如果没有这个截断,大输入会像 x 平方一样增长。输入可以是标量或数组,因此请使用 element-wise 操作。应用场景: MobileNetV3 以及其他为移动端硬件构建的高效视觉模型。
主题
Activations
相似题目
  • 实现 GPT 和 BERT 中的激活函数 GELUEasy
  • 在输入值较大时计算不溢出的 softplusEasy
  • 实现 ELU 及其导数Easy
  • 计算 dead ReLU 单元的比例Easy
所有 Activations 道题目
反馈
218 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def hard_swish(x):
# your code here
pass
​

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

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