[英]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.