CodeBlanks Logo Icon CodeBlanks

Array properties

NumPy arrays have properties like shape, size, ndim, and dtype.

shape, ndim, size

Every array has attributes describing its structure:

a = np.array([[1, 2, 3],
              [4, 5, 6]])
print(a.shape)   # (2, 3)  rows, columns
print(a.ndim)    # 2       number of dimensions
print(a.size)    # 6       total elements

Most ML bugs are shape mismatches; when something goes wrong, the first thing to do is print shape.

dtype

dtype tells the type of the elements. Integers become int64 and decimals float64; in a mixed list NumPy converts everything to decimals:

print(np.array([1, 2]).dtype)      # int64
print(np.array([1, 2.5]).dtype)    # float64
x = np.array([1, 2]).astype(np.float32)
print(x.dtype)                     # float32

Deep learning often uses float32 to save memory; it is converted with astype.

Practice Inspect the array

Print the shape, ndim and size of array a in a single print, separated by spaces.

Starter code

model.py
import numpy as np

a = np.ones((3, 4, 2))

# buraya yaz

Sample solution

model.py
import numpy as np

a = np.ones((3, 4, 2))

print(a.shape, a.ndim, a.size)

Expected output

(3, 4, 2) 3 24

Questions and answers

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

1 What is <code>np.zeros((4, 5)).size</code>?

  • 20 Correct answer
  • 9
  • 2
  • (4, 5)

Explanation: size is the product of all dimensions: 4 × 5 = 20.

2 Convert the array to float32.

Question
x = a.____(np.float32)
Answer
x = a.astype(np.float32)

Explanation: astype returns a copy in the new type; the original array is unchanged.

3 Match the attributes.

Term Meaning
shape Tuple of dimensions
ndim Number of dimensions
size Total elements
dtype Element type

All lessons in Beginner

13 Project: Classification

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