Understand numpy.random.shuffle(): Randomly Permute a Sequence – Numpy Tutorial

By | September 23, 2019

numpy.random.shuffle() function can help us to permute a sequence randomly along the first axis , in this tutorial we will introduce how to use this function correctly.

Syntax

numpy.random.shuffle(x)

Modify the elements randomly along the first axis.

Parameter

x : array_like

Return

This function return None.

Here are some examples on how to use.

import numpy as np
x1 = np.array(range(9)).reshape(3, 3)
x1_seq = np.random.permutation(x1)

print("new x1 = ")
print(x1_seq)
print("x1 = ")
print(x1)

The nex x1 and x1 is:

new x1 = 
[[3 4 5]
 [0 1 2]
 [6 7 8]]
x1 = 
[[0 1 2]
 [3 4 5]
 [6 7 8]]

numpy.random.shuffle(x) is also can permute elements in x randomly, you can read this tutorial to knw how to do.

Understand numpy.random.permutation(): Randomly permute a sequence – Numpy Tutorial

The difference between numpy.random.permutation(x) and numpy.random.shuffle(x)

When x is an array like, both numpy.random.permutation(x) and numpy.random.shuffle(x)  can permute the elements in x randomly along the first axis. However, numpy.random.permutation(x) will return a new varialbe and x is not change, numpy.random.shuffle(x) will change x and does not return a new variable.

Here is an example.

import numpy as np
#create a 4 * 4 matrix
x1 = np.array(range(16)).reshape(4,4)
x2 = np.array(range(16)).reshape(4,4)
print("x1 = ")
print(x1)
print("x2 = ")
print(x2)

Print x1 and x2, the result is:

x1 = 
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]
x2 = 
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]

You will find x1 and x2 are the same.

Permute elements randomly along the first axis of x1 and x2.

x1_seq = np.random.permutation(x1)
np.random.shuffle(x2)

Print new x1 and x1

print("new x1 = ")
print(x1_seq)
print("x1 = ")
print(x1)

The result is:

new x1 = 
[[ 4  5  6  7]
 [ 0  1  2  3]
 [12 13 14 15]
 [ 8  9 10 11]]
x1 = 
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]

You will find x1 is not changed.

Print x2

print("x2 = ")
print(x2)

The result is:

x2 =
[[ 4  5  6  7]
 [12 13 14 15]
 [ 0  1  2  3]
 [ 8  9 10 11]]

You will find x2 is changed.

Leave a Reply

Your email address will not be published. Required fields are marked *