How to shuffle two numpy arrays, so that record indices are stay aligned in both after shuffling?

Viewed 181

I have a 4D array and a 1D array:

import numpy as np

data = np.random.randn(10, 1, 5, 5)    # num_records, depth, height, width
labels = np.array([1,1,1,1,1,0,0,0,0,0])

I want to shuffle the data and labels by num_records to get labels in a random order.

I know that one could use shuffle function: np.random.shuffle(data). But I don't know how to persist the relation between data and labels after shuffling.

2 Answers

This shuffles both arrays together:

import numpy as np

data = np.random.randn(10, 1, 5, 5)    # num_records, depth, height, width
labels = np.array([1,1,1,1,1,0,0,0,0,0])

# shuffle indices
idx = np.random.permutation(range(len(labels)))

# shuffle together
data, labels = data[idx,:,:,:], labels[idx]
Related