If I want to display one image from mnist dataset, I need to reshape it from (1,28,28) to (28,28) using the following code:
import tensorflow as tf
import matplotlib.pyplot as plt
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
sample = x_train[:1].reshape((28,28))
plt.imshow(sample, cmap="gray")
plt.show()
However, if I want to display multiple images within the same plot. I don't need to reshape them with the following code:
import tensorflow as tf
import matplotlib.pyplot as plt
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i 1)
plt.imshow(x_train[i])
plt.show()
Why reshape is not require in the second code?
CodePudding user response:
You wouldn't need reshape in the first one either if you selected the first image using x_train[0]
. Accessing a specific index of the array removes the first element of the shape.
So if you have a numpy array of shape (100, 28, 28), and access x_train[0]
, you will get a shape of (28, 28). But if you access it as x_train[:1]
, you will still have three dimensions: (1, 28, 28).
It does this because you could also do x_train[:2] and take the first two images, so it needs a dimension to keep track of how many images you selected.