np.clip vs np.max 限制下限值

huangapple go评论69阅读模式
英文:

np.clip vs np.max to limit lower value

问题

我可以考虑两种明显的实现方式:

  • np.clip(x, a_min=0, a_max=None)
  • numpy.maximum(0, x)

哪种是更好的选择,为什么?

英文:

Let's say I am trying to codify max(0, x) (the formula for ReLU activation) with numpy, where x is a numpy array.

I can think of two obvious implementations:

  • np.clip(x, a_min=0, a_max=None)
  • numpy.maximum(0, x)

Which is the better choice, and why?

答案1

得分: 3

对于这个特定的应用,numpy.maximum 应该更有效(您只需要 clip 执行的测试之一):

# 设置随机示例
a = np.random.randint(-100, 100, size=1_000_000)

%%timeit
np.maximum(0, x)
9.62 微秒 ± 833 纳秒每循环7每次 100,000 次循环

%%timeit
np.clip(x, a_min=0, a_max=None)
52.5 微秒 ± 9.92 微秒每循环7每次 10,000 次循环
英文:

For this specific application, numpy.maximum should be more efficient (you only need one of the tests performed by clip):

# setting up random example
a = np.random.randint(-100, 100, size=1_000_000)

%%timeit
np.maximum(0, x)
9.62 µs ± 833 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)

%%timeit
np.clip(x, a_min=0, a_max=None)
52.5 µs ± 9.92 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

huangapple
  • 本文由 发表于 2023年4月17日 14:09:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76032125.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定