从 2d numpy 数组的特定行和列中随机抽样(本质上是通过忽略边缘效应进行抽样)

Random sample from specific rows and columns of a 2d numpy array (essentially sampling by ignoring edge effects)

我有一个大小为 100 x 100 的二维 numpy 数组。 我想从“内部”80 x 80 值中随机抽取值,以便我可以排除受边缘效应影响的值。我想从第 10 行到第 90 行以及从第 10 列到第 90 列进行采样。

但是,重要的是,我需要保留 100 x 100 网格中的 原始 索引值,所以我不能只 trim 数据集并继续.如果我这样做,我并没有真正解决边缘效应问题,因为这是在多次迭代的循环中发生的。

gridsize = 100
new_abundances = np.zeros([100,100],dtype=np.uint8)
min_select = int(np.around(gridsize * 0.10))
max_select = int(gridsize - (np.around(gridsize * 0.10)))
row_idx =np.arange(min_select,max_select)
col_idx = np.arange(min_select,max_select)

indices_random = ????? 仅在 row_idx 和 col_idx 集合的行和列内从 new_abundances 随机抽样。

我最终需要的是从展平的 new_abundances 数组中选择的 250 个随机索引的列表。我需要将 new_abundances 数组保持为 2d 以识别“边缘”,但一旦完成,我需要将其展平以获得随机选择的索引。

期望的输出:

扁平化 new_abundances 数组中的一维索引列表。

是否可以解决您的问题?

import numpy as np

np.random.seed(0)
mat = np.random.random(size=(100,100))

x_indices = np.random.randint(low=10, high=90, size=250)
y_indices = np.random.randint(low=10, high=90, size=250)

coordinates = list(zip(x_indices,y_indices))

flat_mat = mat.flatten()
flat_index = x_indices * 100 + y_indices

然后您可以使用 coordinates 列表中的任何值访问元素,例如mat[coordinates[0]] returns coordinates[0] 处的矩阵值。在我的例子中,coordinates[0] 的值是 (38, 45)。如果矩阵为flattened,则可以计算对应元素的一维索引。在这种情况下,mat[coordinates[0]] == flat_mat[flat_index[0]] 成立,其中 flat_index[0]==3845=100*38+45

另请注意,通过这种方式可以对原始数据进行多次采样。

使用您的符号:

import numpy as np
np.random.seed(0)
gridsize = 100
new_abundances = np.zeros([100,100],dtype=np.uint8)
min_select = int(np.around(gridsize * 0.10))
max_select = int(gridsize - (np.around(gridsize * 0.10)))

x_indices = np.random.randint(low=min_select, high=max_select, size=250)
y_indices = np.random.randint(low=min_select, high=max_select, size=250)
coords = list(zip(x_indices,y_indices))

flat_new_abundances = new_abundances.flatten()
flat_index = x_indices * gridsize  + y_indices