Home > Back-end >  x.reshape([1,28,28,1]) reshaping meaning
x.reshape([1,28,28,1]) reshaping meaning

Time:10-05

I can not understand what this reshaping actually do with an array of 28*28.

the code is:

x.reshape([1,28,28,1])

CodePudding user response:

Reshape - as the name suggests - reshapes your array into an array of different shape.

>>> import numpy as np
>>> x = np.arange(28*28)
>>> x.shape
(784,)
>>> y = x.reshape(28,28)
>>> y.shape
(28, 28)
>>> z = y.reshape([1, 28, 28, 1])
>>> z.shape
(1, 28, 28, 1)

A shape of 1 implies that the respective dimension has a length of 1. This is most useful when working with broadcasting, as the array will be repeated along that dimension as needed.

>>> a = np.array([1, 2, 3]).reshape(3, 1)
>>> b = np.array([1, 2, 3]).reshape(1, 3)
>>> a * b
array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])

Another use is to differentiate between row and column vectors, which you can understand as matrices of shape [1, X] or [X, 1] respectively.

>>> row_vector = np.array([1, 2, 3]).reshape(1,3)
>>> row_vector
array([[1, 2, 3]])
>>> column_vector = np.array([1,2,3]).reshape(3,1)
>>> column_vector
array([[1],
       [2],
       [3]])
  • Related