[英]More efficient way to access rows based on a list of indices in 2d numpy array?
所以我有 2d numpay 數組 arr。 這是一個比較大的: arr.shape = (2400, 60000)
我目前正在做的事情如下:
arr.shape[0]
索引arr
索引no_rows = arr.shape[0]
indicies = np.array(range(no_rows))
my_vals = []
for k in range(no_samples):
random_idxs = np.random.choice(indicies, size=no_rows, replace=True)
my_vals.append(
arr[random_idxs].mean(axis=0).max()
)
我的問題是速度很慢。 以我的arr
大小,1 個循環大約需要 3 秒。 因為我想要一個大於 1k 的樣本 - 我目前的解決方案非常糟糕(1k*~3s -> ~1h)。 我已經對其進行了分析,瓶頸是基於索引訪問行。 "mean"
和"max"
工作fast. np.random.choice
fast. np.random.choice
也可以。
你覺得有什么需要改進的地方嗎? 一種更有效的訪問索引的方法,或者更好的更快的方法來解決這個問題?
到目前為止我嘗試了什么:
random_idxs = np.random.choice(sample_idxs, size=sample_size, replace=True)
test = random_idxs.ravel()[arr.ravel()].reshape(arr.shape)
由於高級索引會生成一個副本,因此程序將在arr[random_idxs]
中分配巨大的 memory 。
因此,提高效率的最簡單方法之一就是批量處理。
BATCH = 512
max(arr[random_idxs,i:i+BATCH].mean(axis=0).max() for i in range(0,arr.shape[1],BATCH))
這不是問題的一般解決方案,但應該使您的特定問題更快。 基本上, arr.mean(axis=0).max()
不會改變,那么為什么不從該數組中抽取隨機樣本呢?
就像是:
mean_max = arr.mean(axis=0).max()
my_vals = np.array([np.random.choice(mean_max, size=len(mean_max), replace=True) for i in range(no_samples)])
你甚至可以這樣做: my_vals = np.random.choice(mean_max, size=(no_samples, len(mean_max)), replace=True)
,但我不確定如果有的話,那會如何改變你的統計數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.