Aae*_*Aae 3 python arrays random numpy list
有没有一种有效的方法来创建一个任意长的numpy数组,其中每个维度由从长度> = n的列表中提取的n个元素组成?列表中的每个元素只能为每个维度绘制一次.
例如,如果我有列表l = ['cat', 'mescaline', 'popcorn'],我希望能够,例如通过键入类似的东西np.random.pick_random(l, (3, 2), replace=false),创建一个数组array([['cat', 'popcorn'], ['cat', 'popcorn'], ['mescaline', 'cat']]).
谢谢.
有几种方法可以做到这一点,每种方式都有其优点/缺点,以下四种方式只是从我的头脑中...
random.sample,简单而内置,虽然它可能不是最快的......numpy.random.permutation再简单,但它创建了一个我们必须切片的副本,哎哟!numpy.random.shuffle 因为它在适当的位置进行了改进,所以速度更快,但我们仍需要切片.numpy.random.sample是最快但它只适用于0到1的间隔,所以我们必须将其标准化,并将其转换为整数以获得随机索引,最后我们仍然需要切片,注意归一化为我们想要的大小不生成均匀的随机分布.这是一些基准.
import timeit
from matplotlib import pyplot as plt
setup = \
"""
import numpy
import random
number_of_members = 20
values = range(50)
"""
number_of_repetitions = 20
array_sizes = (10, 200)
python_random_times = [timeit.timeit(stmt = "[random.sample(values, number_of_members) for index in xrange({0})]".format(array_size),
setup = setup,
number = number_of_repetitions)
for array_size in xrange(*array_sizes)]
numpy_permutation_times = [timeit.timeit(stmt = "[numpy.random.permutation(values)[:number_of_members] for index in xrange({0})]".format(array_size),
setup = setup,
number = number_of_repetitions)
for array_size in xrange(*array_sizes)]
numpy_shuffle_times = [timeit.timeit(stmt = \
"""
random_arrays = []
for index in xrange({0}):
numpy.random.shuffle(values)
random_arrays.append(values[:number_of_members])
""".format(array_size),
setup = setup,
number = number_of_repetitions)
for array_size in xrange(*array_sizes)]
numpy_sample_times = [timeit.timeit(stmt = \
"""
values = numpy.asarray(values)
random_arrays = [values[indices][:number_of_members]
for indices in (numpy.random.sample(({0}, len(values))) * len(values)).astype(int)]
""".format(array_size),
setup = setup,
number = number_of_repetitions)
for array_size in xrange(*array_sizes)]
line_0 = plt.plot(xrange(*array_sizes),
python_random_times,
color = 'black',
label = 'random.sample')
line_1 = plt.plot(xrange(*array_sizes),
numpy_permutation_times,
color = 'red',
label = 'numpy.random.permutations'
)
line_2 = plt.plot(xrange(*array_sizes),
numpy_shuffle_times,
color = 'yellow',
label = 'numpy.shuffle')
line_3 = plt.plot(xrange(*array_sizes),
numpy_sample_times,
color = 'green',
label = 'numpy.random.sample')
plt.xlabel('Number of Arrays')
plt.ylabel('Time in (s) for %i rep' % number_of_repetitions)
plt.title('Different ways to sample.')
plt.legend()
plt.show()
Run Code Online (Sandbox Code Playgroud)
结果:

因此,它看起来就像numpy.random.permutation是最差的,并不奇怪,蟒蛇自己random.sample拿着它自己的,所以它看起来像之间的紧密的赛程numpy.random.shuffle,并numpy.random.sample与numpy.random.sample挤开,所以要么就足够了,即使numpy.random.sample有更高的内存占用我还是喜欢它,因为我真的不需要构建数组我只需要随机索引......
$ uname -a
Darwin Kernel Version 10.8.0: Tue Jun 7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386
$ python --version
Python 2.6.1
$ python -c "import numpy; print numpy.__version__"
1.6.1
Run Code Online (Sandbox Code Playgroud)
UPDATE
不幸的是numpy.random.sample,不会从人群中抽取独特的元素,所以你会得到复制,所以坚持洗牌同样快.
更新2
如果你想保持在numpy中以利用它的一些内置功能,只需将值转换为numpy数组.
import numpy as np
values = ['cat', 'popcorn', 'mescaline']
number_of_members = 2
N = 1000000
random_arrays = np.asarray([values] * N)
_ = [np.random.shuffle(array) for array in random_arrays]
subset = random_arrays[:, :number_of_members]
Run Code Online (Sandbox Code Playgroud)
注意,这里的N非常大,因此你将得到重复的排列数,通过排列我的意思是在排列中没有重复值的值的顺序,因为从根本上说,如果只计算任何给定有限集的有限数量的排列如果只选择k个元素n!/(n - k),则整个集合然后是n!即使不是这种情况,意味着我们的集合要大得多,我们仍然可能依赖于随机函数实现重复,因为shuffle/permutation/...等等只适用于当前集合并且不知道对于人口,这可能是可接受的,也可能是不可接受的,取决于你想要实现的目标,如果你想要一组独特的排列,那么你将生成该集合并对其进行二次抽样.
这是使用numpy的方法np.random.randint:
In [68]: l = np.array(['cat', 'mescaline', 'popcorn'])
In [69]: l[np.random.randint(len(l), size=(3,2))]
Out[69]:
array([['cat', 'popcorn'],
['popcorn', 'popcorn'],
['mescaline', 'cat']],
dtype='|S9')
Run Code Online (Sandbox Code Playgroud)
编辑:在每个元素每行最多出现一次的附加细节之后
这不是很节省空间,你需要更好的东西吗?
In [29]: l = np.array(['cat', 'mescaline', 'popcorn'])
In [30]: array([np.random.choice(l, 3, replace=False) for i in xrange(5)])
Out[30]:
array([['mescaline', 'popcorn', 'cat'],
['mescaline', 'popcorn', 'cat'],
['popcorn', 'mescaline', 'cat'],
['mescaline', 'cat', 'popcorn'],
['mescaline', 'cat', 'popcorn']],
dtype='|S9')
Run Code Online (Sandbox Code Playgroud)