0

我想生成一个 2d 随机数组并选择一些(m)随机索引来通过预定义的值改变它们的值(m)

举个例子,我想生成4 by 4矩阵。然后选择4随机索引并使用[105,110,115,120]此值更改它们的值。

random_matrix = np.random.randint(0,100,(4,4))

# array([[27, 20,  2,  8],
#        [43, 88, 14, 63],
#        [ 5, 55,  4, 72],
#        [59, 49, 84, 96]])

现在,我想随机选择4索引并从预定义更改它们的值p_array = [105,110,115,120]

我尝试生成这样的所有索引:

[
    (i,j)
    for i in range(len(random_matrix)) 
    for j in range(len(random_matrix[i])) 
]

但是如何从中选择4随机索引并从预定义中更改它们的值p_matrix?我想不出任何解决方案,因为我必须确保4我卡得很厉害的唯一随机索引,因为随机性并不能保证。

我们可以一次生成随机矩阵并选择索引吗?我需要它,因为如果尺寸m越来越大,它会变得越来越慢(当前实现)。我还必须确保性能。

4

2 回答 2

1

请执行下列操作:

import numpy as np

# for reproducibility
np.random.seed(42)

rows, cols = 4, 4
p_array = np.array([105, 110, 115, 120])

# generate random matrix that will always include all the values from p_array
k = rows * cols - len(p_array)
random_matrix = np.concatenate((p_array, np.random.randint(0, 100, k)))
np.random.shuffle(random_matrix)

random_matrix = random_matrix.reshape((rows, cols))
print(random_matrix)

输出

[[115  33  54  27]
 [  3  27  16  69]
 [ 33  24  81 105]
 [ 62 110  94 120]]

更新

假设与以前相同的设置,您可以执行以下操作,以生成一个知道p_array值索引的随机矩阵:

positions = np.random.permutation(np.arange(rows * cols))
random_matrix = random_matrix[positions].reshape((rows, cols))
print("random-matrix")
print("-------------")
print(random_matrix)
print("-------------")

# get indices in flat array
flat_indices = np.argwhere(np.isin(positions, np.arange(4))).flatten()

# get indices in matrix
matrix_indices = np.unravel_index(flat_indices, (rows, cols))
print("p_array-indices")
print("-------------")
print(matrix_indices)

# verify that indeed those are the values
print(random_matrix[matrix_indices])

输出

random-matrix
-------------
[[ 60  74  20  14]
 [105  86 120  82]
 [ 74  87 110  51]
 [ 92 115  99  71]]
-------------
p_array-indices
-------------
(array([1, 1, 2, 3]), array([0, 2, 2, 1]))
[105 120 110 115]
于 2021-10-26T14:13:53.850 回答
0

您可以使用建议的交叉产品和执行以下操作random.sample

import random
from itertools import product

pool = [*product(range(len(random_matrix)), range(len(random_matrix[0])))]

random_indices = random.sample(pool, 4)
# [(3, 1), (1, 2), (2, 0), (2, 3)]
于 2021-10-26T14:12:05.063 回答