我有一个大小为 46928x28x28
的 numpy 数组,我想将该数组随机拆分为两个大小为 (41928x28x28)
和 (5000x28x28) 的子矩阵
。因此,要从初始数组中随机选择行。到目前为止我尝试的代码(计算两个子数组的索引)如下:
ind = np.random.randint(input_matrix.shape[0], size=(5000,))
rest = np.array([i for i in range(0,input_matrix.shape[0]) if i not in ind])
rest = np.array(rest)
然而,令人惊讶的是 ind 的形状是 (5000,)
而其余的形状是 (42192,)
。在那种情况下我做错了什么?
最佳答案
错误是 randint
给出了一些重复的索引。您可以通过打印 len(set(ind))
来测试它,您会看到它小于 5000。
要使用相同的想法,只需将第一行替换为
ind = np.random.choice(range(input_matrix.shape[0]), size=(5000,), replace=False)
也就是说,由于对列表进行迭代,您的代码的第二行非常慢。使用 bool 值向量定义所需的索引会快得多,这将允许您使用否定运算符 ~
。
choice = np.random.choice(range(matrix.shape[0]), size=(5000,), replace=False)
ind = np.zeros(matrix.shape[0], dtype=bool)
ind[choice] = True
rest = ~ind
在我的机器上,这个方法与实现 scikit.learn 的 train_test_split
一样快,这让我觉得两者在做完全相同的事情。
关于python - 随机拆分一个numpy数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50491630/