numpy 的随机 vs python 的默认随机子采样

numpy's random vs python's default random subsampling

我观察到 python 的默认 random.sample 比 numpy 的 random.choice 快得多。从长度为 100 万的数组中抽取一个小样本,random.sample 比其 numpy 的对应物快 1000 倍以上。

In [1]: import numpy as np

In [2]: import random

In [3]: arr = [x for x in range(1000000)]

In [4]: nparr = np.array(arr)

In [5]: %timeit random.sample(arr, 5)
The slowest run took 5.25 times longer than the fastest. This could mean that an intermediate result is being cached
100000 loops, best of 3: 4.54 µs per loop

In [6]: %timeit np.random.choice(arr, 5)
10 loops, best of 3: 47.7 ms per loop

In [7]: %timeit np.random.choice(nparr, 5)
The slowest run took 6.79 times longer than the fastest. This could mean that an intermediate result is being cached
100000 loops, best of 3: 7.79 µs per loop

尽管从 numpy 数组中进行 numpy 采样的速度相当快,但它比默认的随机采样要慢。

上面的观察是否正确,或者我是否遗漏了 random.samplenp.random.choice 计算之间的区别?

您在第一次调用 numpy.random.choice 时看到的只是将列表 arr 转换为 numpy 数组的开销。

至于你的第二个电话,稍微差一点可能是因为 numpy.random.choice 提供了采样的能力 non-uniformly,并且也可以在有替换和没有替换的情况下进行采样。