代码之家  ›  专栏  ›  技术社区  ›  Gideon Kogan

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

  •  2
  • Gideon Kogan  · 技术社区  · 6 年前

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

    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。有办法避免吗?它确实使代码更加复杂。

    1 回复  |  直到 6 年前
        1
  •  3
  •   FHTMitchell    6 年前

    你看过 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 意思是“不要在这里计算”。在这种情况下 意思是不要计算整个数组。所以才这么快!

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


    where 像这样工作

    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
    

    鉴于使用 外面的 跳过创建临时数组,因此速度稍快。


    从侧面来看,我认为允许 作为一个值有点傻,因为你为什么不想计算函数在任何地方?