Greetings my fellow learners, it is requested to explain why do we use reshape in python?
Please explain why is it used over here?
Let’s add some print statements, so that we can see what is happening there:
x = np.arange(0,20,1)
print(f"x = {x}")
print(f"type(x) = {type(x)}")
print(f"x.shape = {x.shape}")
X = x.reshape(-1,1)
print(f"X = {X}")
print(f"type(X) = {type(X)}")
print(f"X.shape = {X.shape}")
When I run that, here’s what I get:
x = [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
type(x) = <class 'numpy.ndarray'>
x.shape = (20,)
X = [[ 0]
[ 1]
[ 2]
[ 3]
[ 4]
[ 5]
[ 6]
[ 7]
[ 8]
[ 9]
[10]
[11]
[12]
[13]
[14]
[15]
[16]
[17]
[18]
[19]]
type(X) = <class 'numpy.ndarray'>
X.shape = (20, 1)
So what we can see is that the “arange” call gives us a 1D (one dimensional) numpy array with 20 elements. But the “reshape” gives two dimensions, so we end up with a 2D column vector with shape 20 x 1. Note that there is nothing “magic” about the -1 that is used as the first dimension: that just means “use as many elements as you have left here”. The key point is the 1 as the second dimension, which is what gives us the result of a column vector.
If you ever need to use column vector instead of a row one, this particular kind of reshape is inevitable. You need to construct an n x 1 matrix, which is in turn a column vector with n elements. You literally write down numbers below each other, in a column, just like in an n x 1 matrix, n rows x 1 column (n numbers in 1 column).