与随机整数与另一个范围创建numpy的阵列的每一行(Create numpy array with

2019-09-25 21:03发布

我需要使每行中具有不同的范围,生成的随机整数快速numpy的阵列。

通过我的作品,但速度很慢,当我增加向量号300000的代码:

import numpy as np
import random

population_size = 4
vectors_number = population_size * 3 

add_matrix = []
for i in range(0, int(vectors_number/population_size)):
    candidates = list(range(population_size*i, population_size*(i+1))) 
    random_index = random.sample(candidates, 4)
    add_matrix.append(random_index)

winning_matrix = np.row_stack(add_matrix)
print(winning_matrix)

每一行都是选择从可变范围4张的随机数。

输出:

[[ 3  0  1  2]
 [ 4  6  7  5]
 [11  9  8 10]]

最好将通过创建只使用没有循环numpy的是矩阵

Answer 1:

下面是遵循量化方法this trick提取独特的随机样本-

ncols = 4
N = int(vectors_number/population_size)
offset = np.arange(N)[:,None]*population_size
winning_matrix = np.random.rand(N,population_size).argsort(1)[:,:ncols] + offset

我们还可以利用np.argpartition更换的最后一步-

r = np.random.rand(N,population_size)
out = r.argpartition(ncols,axis=1)[:,:ncols] + offset

计时 -

In [63]: import numpy as np
    ...: import random
    ...: 
    ...: population_size = 64
    ...: vectors_number = population_size * 300000

In [64]: %%timeit
    ...: add_matrix = []
    ...: for i in range(0, int(vectors_number/population_size)):
    ...:     candidates = list(range(population_size*i, population_size*(i+1))) 
    ...:     random_index = random.sample(candidates, 4)
    ...:     add_matrix.append(random_index)
    ...: 
    ...: winning_matrix = np.row_stack(add_matrix)
1 loop, best of 3: 1.82 s per loop

In [65]: %%timeit
    ...: ncols = 4
    ...: N = int(vectors_number/population_size)
    ...: offset = np.arange(N)[:,None]*population_size
    ...: out = np.random.rand(N,population_size).argsort(1)[:,:ncols] + offset
1 loop, best of 3: 718 ms per loop

In [66]: %%timeit
    ...: ncols = 4
    ...: N = int(vectors_number/population_size)
    ...: offset = np.arange(N)[:,None]*population_size
    ...: r = np.random.rand(N,population_size)
    ...: out = r.argpartition(ncols,axis=1)[:,:ncols] + offset
1 loop, best of 3: 428 ms per loop


Answer 2:

在你的情况下,循环可以使用压缩map和列表内涵。

winning_matrix = np.vstack ([random.sample (candidate, d2) for candidate in map (lambda i: list(range(population_size*i, population_size*(i+1))), range(0, int(vectors_number/population_size)))])

输出:

array([[ 0,  1,  3,  2],
       [ 5,  6,  4,  7],
       [11, 10,  9,  8]])

这可细分为

# This is your loop generating the arrays from where you are sampling
range_list = map (lambda i: list(range(population_size*i, population_size*(i+1))), range(0, int(vectors_number/population_size)))
# This does the generation of the matrix, using exactly following your method
winning_matrix = np.vstack ([random.sample (candidate, d2) for candidate in range_list])

在产生具有不同范围的随机整数的情况下(而不是从一个样品),可以按照下面的方法。

如何像这样

# Generating upper and lower bounds for each row.
pair_ranges = product (list (range (1, 5)), list (range (5, 9)))
d2 = 4
np.vstack ([np.random.random_integers (x, y, [1, d2]) for x, y in pair_ranges])

输出:

array([[2, 5, 2, 5],
       [5, 6, 2, 4],
       [1, 3, 2, 3],
       [4, 2, 4, 4],
       [2, 6, 4, 6],
       [7, 2, 6, 3],
       [4, 5, 3, 5],
       [4, 6, 3, 6],
       [3, 6, 3, 6]])

该行将具有范围之间的随机整数

array([[1, 5],
       [1, 6],
       [1, 7],
       [2, 5],
       [2, 6],
       [2, 7],
       [3, 5],
       [3, 6],
       [3, 7]])


Answer 3:

因为我们只选择464的碰撞将是罕见的,因此,我们可以用更换和正确绘制之后。

import numpy as np

def multiperm(y, x, factor=16, remap=False):
    draw = np.random.randint(0, factor*x, (y, x))
    idx = np.full((y, factor*x), -1, dtype=np.int8 if factor*x < 128 else int)
    yi, xi = np.ogrid[:y, :x]
    idx[yi, draw] = xi
    yd, xd = np.where(idx[yi, draw] != xi)
    while yd.size > 0:
        ndraw = np.random.randint(0, factor*x, yd.shape)
        draw[yd, xd] = ndraw
        good = idx[yd, ndraw] == -1
        idx[yd[good], ndraw[good]] = xd[good]
        good[good] = idx[yd[good], ndraw[good]] == xd[good]
        yd, xd = yd[~good], xd[~good]
    if remap:
        idx = np.zeros((y, factor*x), dtype=np.int8)
        idx[yi, draw] = 1
        idx[0, 0] -= 1
        return idx.ravel().cumsum().reshape(idx.shape)[yi, draw]
    else:
        return draw + factor*x*yi

from timeit import timeit

print(timeit("multiperm(300_000, 4)", globals=globals(), number=100)*10, 'ms')

# sanity checks
check = multiperm(300_000, 4)
print(np.all(np.arange(300_000) * 64 <= check.T) and np.all(np.arange(1, 300_001) * 64 > check.T))
print(len(set(check.ravel().tolist())) == check.size)

样品运行:

44.83660604993929 ms
True
True


Answer 4:

重温与问题,更好地了解,认识仅需要64人口的第一随机4的结果,我来到了这个答案。 还有一个循环,但它是一个循环过少数所需的列,它基本上交换唯一的第一4(入围)列与氨基酸随机其他柱:

import numpy as np

PLAYERS   = 64      # per game
GAMES     = 300000
FINALISTS = 4       # we only want to know the first four

# every player in every game has a unique id
matrix = np.arange(PLAYERS * GAMES).reshape((GAMES, PLAYERS))

games  = np.arange(GAMES)
swaps  = np.random.randint(0, PLAYERS, size=(FINALISTS, GAMES))

for i in range(FINALISTS):
    # some trickey stuff to create tuples for indexing
    dst = tuple(np.vstack([ games, i * np.ones(GAMES, dtype=np.int) ]))
    src = tuple(np.vstack([ games, swaps[i] ]))
    # do the a swap for location i 
    matrix[dst], matrix[src] = matrix[src], matrix[dst]

winning_matrix = matrix[:,:FINALISTS]
print(winning_matrix)


文章来源: Create numpy array with random integers each row with another range