Skip to content Skip to sidebar Skip to footer

Randomly Shuffle Data And Labels From Different Files In The Same Order

l have two numpy arrays the first one contains data and the second one contains labels. l want to shuffle the data with respect to their labels. In other way, how can l shuffle my

Solution 1:

Generate a random order of elements with np.random.permutation and simply index into the arrays data and classes with those -

idx = np.random.permutation(len(data))
x,y = data[idx], classes[idx]

Solution 2:

Alternatively you can concatenate the data and labels together, shuffle them and then separate them into input x and label y as shown below:

defread_data(filename, delimiter, datatype): # Read data from a filereturn = np.genfromtxt(filename, delimiter, dtype= datatype)

classes = read_data('labels.csv', dtype= np.str , delimiter='\t')
data = read_data('data.csv', delimiter=',')
dataset = np.r_['1', data, classes] # Concatenate along second axisdefdataset_shuffle(dataset): # Returns separated shuffled data and classes from dataset 
    np.random.shuffle(dataset)
    n, m = dataset.shape
    x = data[:, 0:m-1]
    y = data[:, m-1]
    return x, y # Return shuffled x and y with preserved order

Post a Comment for "Randomly Shuffle Data And Labels From Different Files In The Same Order"