# Shaping

Lesson 11 Chapter 4

# Import Numpy library import numpy as np # Create a matrix A = np.array([[2,1,3,4],[5,2,9,4],[5,2,10,1]]) print('A=\n', A) print('Shape of A=\n', A.shape) # Reshape A to the new shape of (2,6) B = A.reshape(2,6) print("B: \n", B) # Reshape A to the new shape of (2,x) # If we use -1, the remaining dimension will be chosen automatically. C = A.reshape(4,-1) print("C: \n", C) # Flatten operation print("Flatten A: \n", A.ravel())

A= [[ 2 1 3 4] [ 5 2 9 4] [ 5 2 10 1]] Shape of A= (3, 4) B: [[ 2 1 3 4 5 2] [ 9 4 5 2 10 1]] C: [[ 2 1 3] [ 4 5 2] [ 9 4 5] [ 2 10 1]] Flatten A: [ 2 1 3 4 5 2 9 4 5 2 10 1]

The question is how reshaping operations work? Above we had the matrix of size with 12 () total elements. When we use **np.reshape**, the default Numpy order is **“C-style”**, which is, the rightmost index “changes the fastest” for the processing operation. *Let's use the above example* of using **.ravel()** to flatten the matrix: The first element is obviously and the next one is . The processing and creating the new array is as below when using **.ravel()**: