我遇到一个问题,根据随机抛硬币的结果,我必须从字符串中采样随机起始位置。如果这个随机位置的采样在字符串上是均匀的,我想到了两种方法来实现:一种使用 numpy.random 中的多项式,另一种使用 Python 标准库的简单 randint 函数。我测试如下:
from numpy import *
from numpy.random import multinomial
from random import randint
import time
def use_multinomial(length, num_points):
probs = ones(length)/float(length)
for n in range(num_points):
result = multinomial(1, probs)
def use_rand(length, num_points):
for n in range(num_points):
rand(1, length)
def main():
length = 1700
num_points = 50000
t1 = time.time()
use_multinomial(length, num_points)
t2 = time.time()
print "Multinomial took: %s seconds" %(t2 - t1)
t1 = time.time()
use_rand(length, num_points)
t2 = time.time()
print "Rand took: %s seconds" %(t2 - t1)
if __name__ == '__main__':
main()
输出为:
多项式耗时:6.58072400093 秒 兰德花费:2.35189199448秒
看起来 randint 更快,但对我来说仍然很慢。有没有一种矢量化方法可以使用 numpy 或 scipy 使其更快?
谢谢。
最佳答案
我更改了您的代码以实际返回值(并使用 randint
而不是 rand
- 这不是您的意思吗?)就像这样......
def use_multinomial(length, num_points):
probs = ones(length)/float(length)
return multinomial(1, probs, num_points)
def use_rand(length, num_points):
return [randint(1,length) for _ in range(num_points)]
然后我尝试了自己的版本,使用 numpy.random.randint
在字符串上生成随机点的 numpy 数组:
def use_np_randint(length, num_point):
return nprandint(1, length, num_points)
结果:
Multinomial took: 13.6279997826 seconds
Rand took: 0.185000181198 seconds
NP randint took: 0.00100016593933 seconds
相比之下,多项式显然确实很慢,但这就是您想要的吗?我以为你说你想要统一分布?使用 numpy 的 randint 显然是其中最快的。
关于python - 使用 numpy/scipy 在 python 中均匀有效地采样整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2618400/