Numpy:如何将矩阵随机分割/选择为n个不同的矩阵

day*_*mer 13 python random numpy scipy scikits

  • 我有一个形状为(4601,58)的numpy矩阵.
  • 我想根据行数按60%,20%,20%的比例随机分割矩阵
  • 这是我需要的机器学习任务
  • 是否存在随机选择行的numpy函数?

HYR*_*YRY 18

你可以使用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):]
Run Code Online (Sandbox Code Playgroud)


ogr*_*sel 7

如果你想要使用相同的第一维来一致地改组几个数组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]
Run Code Online (Sandbox Code Playgroud)

然后按照HYRY的回答继续进行每个混洗数组的拆分.