代码之家  ›  专栏  ›  技术社区  ›  Sun Bear

优化NumPy脚本

  •  0
  • Sun Bear  · 技术社区  · 6 年前

    我编写了下面的numpython测试脚本来获得某些输入的正态分布。我想我可能没有有效地使用NumPy的向量运算来处理输入数据。
    你能给我演示一下处理输入的方法吗?

    import numpy as np
    
    #Inputs
    mu = np.array( [1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='uint8' )
    sigma = np.array( [1., 1., 1., 1., 1., 3., 3., 3., 3., 3.] )
    number = np.array( [ 5, 10, 15, 20, 25, 25, 20, 15, 10, 5 ], dtype='uint16' )
    
    #Processing
    np.random.seed(0)
    norms = [  np.random.normal(i, sigma[n], number[n]) for n, i in enumerate(mu) ]
    print( norms )
    
    a = np.concatenate( [ np.ceil(i) for i in norms ] )
    print( a )
    
    #Output
    result = np.histogram( a, bins=np.arange(np.amin(a), np.amax(a)+1, 1, dtype='uint8' ) )
    print( result )
    
    0 回复  |  直到 6 年前
        1
  •  2
  •   Quang Hoang    6 年前

    将代码矢量化的一种方法是生成随机标准正态样本并相应地缩放:

    np.random.seed(0)
    
    # random samples
    samples = np.random.normal(size=number.sum())
    
    # scale
    samples = samples*sigma.repeat(number) + mu.repeat(number)
    
    # equivalent to your `a`
    out = np.ceil(samples)
    
    # visualize to compare output:
    fig, axes = plt.subplots(1, 2)
    
    axes[0].hist(out, bins=np.arange(out.min(), out.max()+1))
    axes[0].set_title('my code')
    
    axes[1].hist(a, bins=np.arange(a.min(), a.max()+1))
    axes[1].set_title('yours')
    

    输出:

    enter image description here