CodeBlanks Logo Icon CodeBlanks

Reshaping arrays

The reshape() method changes the array's shape while keeping the total element count.

reshape

reshape gives an array a new shape without changing the number of elements. The product of the new shape must equal the old size:

a = np.arange(6)          # [0 1 2 3 4 5]
print(a.reshape(2, 3))    # [[0 1 2] [3 4 5]]
print(a.reshape(3, -1))   # -1: work out the columns -> (3, 2)
# a.reshape(4, 2)  ValueError: 6 elements don't fit into 8

The elements are placed row by row (C order).

flatten and transpose

flatten() reduces the array to one dimension; .T turns rows into columns:

m = np.array([[1, 2, 3],
              [4, 5, 6]])
print(m.flatten())   # [1 2 3 4 5 6]
print(m.T.shape)     # (3, 2)
print(m.T)           # [[1 4] [2 5] [3 6]]

With image data, turning 28×28 pixels into a vector of length 784 before giving it to a neural network is a common step.

Practice Reshape

Turn the array np.arange(1, 13) into a matrix with 3 rows (use -1). Print the matrix, then the shape of its transpose.

Starter code

model.py
import numpy as np

a = np.arange(1, 13)

# buraya yaz

Sample solution

model.py
import numpy as np

a = np.arange(1, 13)

m = a.reshape(3, -1)
print(m)
print(m.T.shape)

Expected output

[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
(4, 3)

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is invalid for an array of 12 elements?

  • reshape(2, -1)
  • reshape(2, 2, 3)
  • reshape(5, -1) Correct answer
  • reshape(3, 4)

Explanation: 12 isn't divisible by 5, so -1 can't be worked out and a ValueError occurs.

2 Reduce the array to one dimension.

Question
v = m.____()
Answer
v = m.flatten()

Explanation: flatten always returns a new one-dimensional copy.

3 Match the operations with the resulting shapes (a = np.arange(12)).

Term Meaning
a.reshape(3, 4) (3, 4)
a.reshape(3, 4).T (4, 3)
a.reshape(2, -1) (2, 6)
a.reshape(2, 6).flatten() (12,)

All lessons in Beginner

13 Project: Classification

  1. Preparing data
  2. Training model
  3. Prediction
  4. Evaluation