假设我正在尝试使用 numpy 编写 max(0, x)
( ReLU activation 的公式),其中 x
是一个 numpy 数组。
我可以想到两个明显的实现:
np.clip(x, a_min=0, a_max=None)
numpy.maximum(0, x)
哪个是更好的选择,为什么?
最佳答案
对于此特定应用,numpy.maximum
应该会更高效(您只需要由 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)
关于python - np.clip 与 np.max 限制较低值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76032125/