两个 100X100 多维数组的随机样本,在 Python Numpy 中具有相同的行号



我在numpy中有两个多维数组(矩阵(,一个是训练集(100,100维(,另一个是类标签(100X1维(我想使用np.random.choice随机抽取样本,但不知道如何弄清楚从两个矩阵中获取相同的行号。

例如,

k=np.random.choice(10,replace=False)
temp_data=data.ix[k]
temp_datat=datat.ix[k]

这是否适用于从我的数组数据和数据中采样 10 个相同的随机行?

与@Umang Gupta建议的方法不同,如果您还想跟踪未选择的方法,可能会有所帮助

# Suppose X_train is your 100 x 100 dataset
# and y_train is your array of labels
idx = np.arange(len(X_train))
np.shuffle(idx)
NUM_SAMPLES = 50
sampled_idxs = idx[:NUM_SAMPLES]
rest_idxs = idx[NUM_SAMPLES:]
X_samples = X_train[sampled_idxs]
X_rest = X_train[rest_idxs]
y_samples = y_train[sampled_idxs]
y_rest = y_train[rest_idxs]

如果您已经安装了Scikit-Learn,则可以使用test_train_split

from sklearn.model_selection import test_train_split
X_samples, X_rest, y_samples, y_rest = train_test_split(X_train, y_train,
train_size=NUM_SAMPLES,
random_state=123)

您可以利用出色的numpy.random.randint()来实现此目的。一个完整的工作示例如下:

# toy data
In [29]: train_set = np.random.random_sample((100, 100))
# of course, class labels have to be discrete :)
In [30]: class_label = np.random.random_sample((100, 1))
# number of samples that need to be picked (a.k.a batch_size)
In [31]: num_samples = 5
# generate sample indices in the range of 100
In [32]: sample_idxs = np.unique(np.random.randint(train_set.shape[0], size=num_samples))
In [33]: sample_idxs
Out[33]: array([24, 30, 37, 73, 74])
# index into the array to get the actual entries
In [34]: (train_set[sample_idxs]).shape
Out[34]: (5, 100)
# index into the class_label array to get the corresponding label entries    
In [35]: (class_label[sample_idxs]).shape
Out[35]: (5, 1)

不过,可能有一个警告。即使多次运行,您也可能无法对整个数据集进行采样。此外,同一示例可能会在多个训练运行中使用。

您可以生成一个随机选择并选择同一行吗?

像这样的事情,

k = np.random.choice(100, 10, replace=True)
row1 = arr1[k]
row2 = arr2[k]

这将适用于 10 行。第一个参数是要选取的数字(0-99,包括 0-99(,第二个参数是要选取的元素数。

最新更新