代码之家  ›  专栏  ›  技术社区  ›  Baz

方波函数在numpy阵列中的应用

  •  0
  • Baz  · 技术社区  · 5 年前

     cos_f = np.vectorize(lambda x: math.cos(2 * math.pi * x))
     signal = square_f(integral)
    

    但是,如果我尝试这样做:

     square_f = np.vectorize(lambda x: sig.square(2 * math.pi * x))
     signal = square_f(integral)
    

    integral 长度为1024,用作缓冲区。

    我应该如何将方波应用于我的信号?

    1 回复  |  直到 5 年前
        1
  •  1
  •   mathfux    5 年前

    sig.square(2*np.pi * x) 比…慢三倍 np.cos(2*np.pi * x) 然而,这并不是瓶颈。这个不错 np.vectorize -基础装修实际花费120倍!发生这种情况的原因是 square_f scipy.signal.square 在被迭代的项上,这是一组设计用来处理数组的算术(不像 math.cos ). 这是一个在内部完成的算术示例 scipy.signal.square公司 :

    def example(x, w=0.5):
        return (1 - (w > 1) | (w < 0)) & (np.mod(x, 2 * pi) < w * 2 * np.pi)
    

    arr 是一个大数组,这显然是更有效的调用 example(arr) 而不是

    ex = np.vectorize(lambda x: example(x))
    ex(arr)
    

    arr = np.linspace(0,1,1000000)
    %timeit ex(arr)
    %timeit example(arr)
    8.13 s ± 208 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    18.5 ms ± 1.14 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
    
        2
  •  3
  •   scleronomic    5 年前

    我不确定你是否需要 np.vectorize

    import numpy as np
    from scipy import signal as sig
    
    integral = np.linspace(0, 10, 1024)
    signal1 = np.cos(2*np.pi * integral)
    signal2 = sig.square(2*np.pi * integral)
    

    当然,您也可以创建一个函数,然后用 作为输入的数组:

    def cos2pi(x):
        return np.cos(2*np.pi * x)
    
    signal1 = cos2pi(integral)
    

    我们可以更进一步,对所有样本同时调用函数一次。

    samples = np.random.random((60000, 1024))
    signal1 = cos2pi(samples)