What does this python syntax mean?

I’m trying to understand the following syntax:

permutation = list(np.random.permutation(m))
shuffled_X = X[:, permutation]
shuffled_Y = Y[:, permutation].reshape((1, m))


first_mini_batch_X = shuffled_X[:, 0 : mini_batch_size]
second_mini_batch_X = shuffled_X[:, mini_batch_size : 2 * mini_batch_size]

In the first example, I don’t understand what’s happening with permutations. and In both, I don’t understand the syntax of putting a comma after a ; while indexing a list.

any help would be much appreciated.

Hi, @ocg.

The , separates dimensions. Here shuffled_X is a two-dimensional array of shape (input size, number of examples), so shuffled_X[:, 0 : mini_batch_size] selects all inputs (:) for the first mini_batch_size examples (0 : mini_batch_size).

np.random.permutation returns a permuted range from 0 to m-1, so X[:, permutation] selects all inputs (:) for all the examples arranged in a random order determined by permutation (i.e., it shuffles the examples).

NumPy’s documentation explains it much better, so I recommend you take a look at it too :slight_smile:

1 Like

Hi @nramon,

Thank you for the explanation. Since

shuffled_Y = Y[:, permutation]

keeps the same shape as Y, I am wondering why do we need to reshape shuffled_Y using:

shuffled_Y = Y[:, permutation].reshape((1, m))

but not shuffled_X?

Hi @amin.pahlavani,

I believe the reshape method is to prevent the loss of a dimension with size 1 that sometimes occurs when dealing with numpy arrays.

In the case of shuffled_X it is not necessary since its shape is (input size, number of examples) which are presumibly not of size 1.

1 Like


That now makes sense.

Thank you!