Skip to main content
 首页 » 编程设计

python之PIck 从二维矩阵中随机抽取样本并将索引保存在 python 中

2024年10月01日8虾米姐

我有一个带有 python 数据的 numpy 二维矩阵,我想通过保留 25% 的初始样本来执行下采样。为此,我使用了以下 random.randint 功能:

reduced_train_face = face_train[np.random.randint(face_train.shape[0], size=300), :] 

但是,我有第二个矩阵,其中包含与面部相关的标签,我想用同样的方式减少。如何保留缩减矩阵中的索引并将它们应用于 train_lbls 矩阵?

请您参考如下方法:

您可以在应用提取之前固定种子:

import numpy as np 
 
# Each labels correspond to the first element of each line of face_train 
labels_train =  np.array(range(0,15,3)) 
face_train = np.array(range(15)).reshape(5,3) 
np.random.seed(0) 
reduced_train_face = face_train[np.random.randint(face_train.shape[0], size=3), :] 
np.random.seed(0) 
reduced_train_labels = labels_train[np.random.randint(labels_train.shape[0], size=3)] 
 
print(reduced_train_face, reduced_train_labels) 
# [[12, 13, 14], [ 0,  1,  2], [ 9, 10, 11]], [12,  0,  9] 

同样的种子,同样的减少。

编辑:我建议你使用np.random.choice(n_total_elem, n_reduce_elem)为了确保您只选择每个数据一次而不是两次相同的数据