Alex Rivera | Logout

Numpy: How to randomly split/select an matrix into n-different matrices

Asked 2012-02-01T00:33:48.637
14
  • I have a numpy matrix with shape of (4601, 58).
  • I want to split the matrix randomly as per 60%, 20%, 20% split based on number of rows
  • This is for Machine Learning task I need
  • Is there a numpy function that randomly selects rows?
Edit
Report

1 Answer

8

A complement to HYRY's answer if you want to shuffle consistently several arrays x, y, z with same first dimension: x.shape[0] == y.shape[0] == z.shape[0] == n_samples.

You can do:

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]

And then proceed with the split of each shuffled array as in HYRY's answer.

answered 2012-02-01T08:18:21.123

Your Answer