2017-06-29 106 views
1

我有以下功能,它需要一個浮點型數組和浮點數作爲其參數。數組中的每一行'計數'是某個實驗的結果,我想隨機繪製一個實驗列表並添加它們,然後重複此過程以創建大量樣本組。優化功能切片numpy陣列

def my_function(counts,nSamples): 
    ''' Create multiple randomly drawn (with replacement) 
     samples from the raw data ''' 
    nSat,nRegions = counts.shape 
    sampleData = np.zeros((nSamples,nRegions)) 
    for i in range(nSamples): 
     rc = np.random.randint(0,nSat,size=nSat) 
     sampleData[i] = counts[rc].sum(axis=0) 
    return sampleData 

這個功能似乎很慢,通常計數有大約10萬行(4列)和NSAMPLES是在2000年左右我一直在使用numba和隱式for循環,試圖加快這個代碼沒有成功嘗試。 有什麼其他方法可以嘗試提高速度?

我已經在函數上運行cProfile並獲得了以下輸出。

8005功能60.208秒

調用排序:標準名稱

ncalls tottime percall cumtime percall filename:lineno(function) 

    1 0.000 0.000 60.208 60.208 <string>:1(<module>) 

2000 0.010 0.000 13.306 0.007 _methods.py:31(_sum) 

    1 40.950 40.950 60.208 60.208 optimize_bootstrap.py:25(bootstrap) 

    1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 

2000 5.938 0.003 5.938 0.003 {method 'randint' of 'mtrand.RandomState' objects} 

2000 13.296 0.007 13.296 0.007 {method 'reduce' of 'numpy.ufunc' objects} 

2000 0.015 0.000 13.321 0.007 {method 'sum' of 'numpy.ndarray' objects} 

    1 0.000 0.000 0.000 0.000 {numpy.core.multiarray.zeros} 

    1 0.000 0.000 0.000 0.000 {range} 

回答

0

你肯定

rc = np.random.randint(0,nSat,size=nSat)

是你想要什麼,而不是size=someconstant?否則,你總結了所有重複的行。


編輯 它有助於一個矩陣產品一共更換切片:

rcvec=np.zeros(nSat,np.int) for i in rc: rcvec[i]+=1 sampleData[i] = rcvec.dot(counts)

(也許有在numpy的一個功能,可以給你rcvec更快)

+0

是的,我正在做一個引導分析 – Jack

+0

我明白了。上述有幫助嗎? –

0

只需一次性生成所有指數,2D大小爲np.random.randint,使用這些索引編入counts陣列,然後沿着第一個軸求和,就像你用loopy處理一樣。

因此,一個量化的方式,因此更快的一個,會是像這樣 -

RC = np.random.randint(0,nSat,size=(nSat, nSamples)) 
sampleData_out = counts[RC].sum(axis=0)