Today I was “fighting” with the numpy reshape function and I found something strange like matrix.reshape(1, -1). Thus, I have researched quite some time and I found, that the -1 is actually a placeholder for python to change the dimensions of the array, given the other dimensions.
E.g., if you declare the following matrix:
1 2 3 4 5 6 |
matrix = np.matrix([ [1,2,3], [6,7,8], [10,11,12], [100,200,300], ]) |
Then, you may kindly ask python to change its dimensions to “6” in rows and whatever is left as a column. “Whatever is left” in our case is 2, and this “whatever” is presented as -1. Thus the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import numpy as np matrix = np.matrix([ [1,2,3], [6,7,8], [10,11,12], [100,200,300], ]) print("original:") print(matrix) reshaped = matrix.reshape(6, -1) print("\n\nmatrix.reshape(6, -1)") print(reshaped) |
kindly presents:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
original: [[ 1 2 3] [ 6 7 8] [ 10 11 12] [100 200 300]] matrix.reshape(6, -1) [[ 1 2] [ 3 6] [ 7 8] [ 10 11] [ 12 100] [200 300]] |
If you want to try the rest of the reshape() function, then I will not take the fun away from you, by telling you the results:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import numpy as np matrix = np.matrix([ [1,2,3], [6,7,8], [10,11,12], [100,200,300], ]) print("original:") print(matrix) reshaped = matrix.reshape(6, -1) print("\n\nmatrix.reshape(6, -1)") print(reshaped) reshaped = matrix.reshape(1, -1) print("\n\nmatrix.reshape(1, -1)") print (reshaped) reshaped = matrix.reshape(-1, 1) print("\n\nmatrix.reshape(-1, 1)") print (reshaped) reshaped = matrix.reshape(-1, 6) print("\n\nmatrix.reshape(-1, 1)") print(reshaped) reshaped = matrix.reshape(2, -1) print("\n\nmatrix.reshape(2, -1)") print (reshaped) #Here we do not even use -1! reshaped = matrix.reshape(6, 2) print("\n\nmatrix.reshape(6, 2)") print (reshaped) reshaped = matrix.reshape(-1, 4) print("\n\nmatrix.reshape(-1, 4)") print (reshaped) |
Use it wisely! 😉