[英]Optimizing NumPy script that calculates Normal Distribution
我编写了以下 NumPy-Python 测试脚本来获取某些输入的正态分布。 我想我可能没有有效地使用 NumPy 的向量运算来处理输入数据。
你能告诉我处理输入的 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 )
向量化代码的一种方法是生成随机标准正态样本并相应地缩放:
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')
Output:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.