我在NumPy中有两个多维数组(矩阵),一个是训练集(100×100维度),另一个是类别标签(100×1维度)。我想使用np.random.choice进行随机抽样,但我不知道如何从两个矩阵中抽取相同行号的样本。
例如,
k=np.random.choice(10,replace=False)temp_data=data.ix[k]temp_datat=datat.ix[k]
这种方法能否从我的两个数组data和datat中抽取10个相同的随机行?
回答:
与@Umang Gupta建议的方法不同,如果你也想追踪未被选中的样本,可能有帮助
# 假设X_train是你的100 x 100数据集# 而y_train是你的标签数组idx = np.arange(len(X_train))np.shuffle(idx)NUM_SAMPLES = 50sampled_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_splitX_samples, X_rest, y_samples, y_rest = train_test_split(X_train, y_train, train_size=NUM_SAMPLES, random_state=123)