I dont understand this code starting from the loop? What should I learn to understand this?

Hi, @Arisha_Prasain

In this cell, all that is being done is to create a figure containing images of numbers. So we start with fig, axes = plt.subplots(4, 4, figsize=...) this will generate and a matplotlib figure with 16 axis or 4 rows by 4 columns. The type of axes is just a 2D Numpy array containing 16 axis and axes.flat will create a single list (iterable) containing all 16 axis and we just loop over.

Now, for the use of np.random.randint(m) this is just to randomly pick a number from 0 to m which will insure that it is in the training examples X, and then we just index this training examples with the random number and get a single example which is just an image.

Now, for the ax.imshow(...) this is just a function in matplotlib that can draw an image from 2D NumPy data.

More information can be found here.

Best regards,
Moaz

1 Like

But why is the image reshaped and then transposed?

Hi @Arisha_Prasain,

The X matrix comes with m images of 20x20 pixels ‘unrolled’, so each is a vector of 1x400. As you know, the reshape will take one of these rows and convert it back to a 20x20. At this point, you have an image in your X_reshaped variable.

To understand the .T at the end of the reshape, I suggest you run this experiment:

Plot the image without the transpose, and see what is plotted. Then plot it with the .T (well, we did already). What can we conclude from this?

Juan

1 Like

When plotted without .T, the image was inverted. So, the aim was to convert each row(which represented an image in a 1 by 400 array form) into a 20*20 pixel erect image, right?

Also, I don’t know how the image was unrolled into the 1*400 vector in the first place?

"When plotted without .T, the image was inverted. " Exactly! That’s why you need to transpose the result.

“So, the aim was to convert each row(which represented an image in a 1 by 400 array form) into a 20*20 pixel erect image, right?” Right on this too!

" I don’t know how the image was unrolled into the 1*400 vector in the first place?" If you read towards the top of the lab, you’ll see that you are given this X matrix with m samples of 20x20 images unrolled in 1x400 vectors each. So that’s data that is provided.

1 Like

Thank you so much! It is much more clearer now.

1 Like