英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论