reshape() changes an array's shape without changing the number of data elements. For example, you can turn a 1-D array with 9 elements into a 3x3 matrix. But if you try to reshape those same 9 elements into a 2x5, you'll get an error because that needs 10 slots.
import numpy as np
numbers = np.arange(1, 10)
print("Original:", numbers)
print("Original shape:", numbers.shape)
matrix = numbers.reshape((3, 3))
print("
3x3 matrix:
", matrix)
flattened = matrix.reshape(-1)
print("
Back to 1-D:", flattened)np.arange(1, 10) produces 9 elements, from 1 to 9. reshape((3, 3)) turns that into 3 rows and 3 columns. reshape(-1) tells NumPy, "work out the size you need and flatten this back to 1-D yourself."
Original: [1 2 3 4 5 6 7 8 9] Original shape: (9,) 3x3 matrix: [[1 2 3] [4 5 6] [7 8 9]] Back to 1-D: [1 2 3 4 5 6 7 8 9]Info
-1 should only be used in one spot in a reshape call. NumPy figures out the missing dimension from the rest.