gpt4 book ai didi

python - 为什么 where 参数默认值为 false?

转载 作者:太空宇宙 更新时间:2023-11-04 00:16:05 25 4
gpt4 key购买 nike

以下代码演示了三种语法形式的计算时间差异。

import numpy as np

a = np.random.randn(10000000)
b = np.zeros(a.shape)

np.sin(a, out=b, where=False)
# 100 loops, best of 3: 6.61 ms per loop
b = np.sin(a)
# 10 loops, best of 3: 162 ms per loop
np.sin(a, out=b)
# 10 loops, best of 3: 146 ms per loop

我想使用提供最短计算时间的语法。我的问题是:为什么如果我定义 out=b,where 参数的默认值仍然是 True。有办法避免吗?这确实使代码更加复杂。

最佳答案

你看过np.sin(a, out=b, where=False)的输出吗?

a = np.linspace(0, 2*np.pi, 10)
# a: array([0. , 0.6981317 , 1.3962634 , 2.0943951 , 2.7925268 ,
# 3.4906585 , 4.1887902 , 4.88692191, 5.58505361, 6.28318531])

b = np.zeros_like(a) # [0, 0, 0, ...]

np.sin(a, out=b, where=False)
# --> b: array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

全为零,因为 False 的值意味着“不要在这里计算”。在这种情况下,False 表示不计算整个数组。这就是它如此之快的原因!

https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.sin.html


哪里是这样的

x = np.ones(3)  # [1,1,1]

np.divide(x, 2, where=[True, False, True])
# --> array([0.5, 1. , 0.5])

所以我们可以说我们只想在某些地方应用该功能。


out 只是表示我们会将结果存储在预先分配的数组中。这允许我们节省内存 np.log(x, out=x) #only use x 或节省数组创建时间(假设我们在一个循环中进行许多计算)。

区别在于 b = np.log(a) 实际上是:

__temp = np.empty(a.shape)  # temporary hidden array
np.log(a, out=__temp)
b = __temp # includes dereferencing old b -- no advantage to initialising b before
del __temp

而使用 out 会跳过创建临时数组,因此速度稍快。


附带说明一下,我认为允许 False 作为值有点愚蠢,因为您为什么不想在任何地方计算函数?

关于python - 为什么 where 参数默认值为 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50927014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com