Numpy:如何将一个矩阵随机拆分/选择成n个不同的矩阵

2024-04-28 07:07:35 发布

您现在位置:Python中文网/ 问答频道 /正文

  • 我有一个核矩阵的形状(460158)。
  • 我想按60%,20%,20%的行数随机拆分矩阵
  • 这是我需要的机器学习任务
  • 是否有随机选择行的numpy函数?

Tags: 函数numpy机器矩阵形状
3条回答

你可以使用numpy.random.shuffle

import numpy as np

N = 4601
data = np.arange(N*58).reshape(-1, 58)
np.random.shuffle(data)

a = data[:int(N*0.6)]
b = data[int(N*0.6):int(N*0.8)]
c = data[int(N*0.8):]

如果您想用相同的第一维连续地洗牌多个数组x,y,z,HYRY的答案的一个补充:x.shape[0] == y.shape[0] == z.shape[0] == n_samples

你可以:

rng = np.random.RandomState(42)  # reproducible results with a fixed seed
indices = np.arange(n_samples)
rng.shuffle(indices)
x_shuffled = x[indices]
y_shuffled = y[indices]
z_shuffled = z[indices]

然后像海瑞的回答那样,对每个洗牌数组进行分割。

如果要随机选择行,可以使用标准Python库中的random.sample

import random

population = range(4601) # Your number of rows
choice = random.sample(population, k) # k being the number of samples you require

无需替换的random.sample示例,因此不必担心重复的行会在choice中结束。给定一个名为matrix的numpy数组,您可以通过切片来选择行,如下所示:matrix[choice]

当然,k可以等于总体中的总元素数,然后choice将包含行索引的随机顺序。然后你可以根据自己的需要对choice进行分区。

相关问题 更多 >