Tools
Text

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 \mathbf{A} of size (3,4) with 12 (3 \times 4) 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 \mathbf{A}_{0,0} and the next one is \mathbf{A}_{0,1}. The processing and creating the new array is as below when using .ravel():

    \[[ \mathbf{A}_{0,0}, \mathbf{A}_{0,1}, \mathbf{A}_{0,2}, \mathbf{A}_{0,3},  \mathbf{A}_{1,0}, \cdots, \mathbf{A}_{3,3}, \mathbf{A}_{3,4} ]\]

Pen
Scroll to Top