首页 > 解决方案 > 两个 100X100 多维数组的随机样本,具有相同的行号。在 python 中

问题描述

我在 numpy 中有两个多维数组(矩阵),一个是训练集(100,100 维),另一个是类标签(100X1 维)我想使用 np.random.choice 随机抽样,但不知道如何计算拿出同一排没有。从两个矩阵。

例如,

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

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

标签: pythonnumpymachine-learningrandomnumpy-ndarray

解决方案


@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)

推荐阅读