Skip to main content

P2 — NumPy Arrays and Shapes

About 55 min

Read P1 — Reading Python for ML Labs first if lists, calls, or imports are unfamiliar. P2 is optional, before L1.1, and needs no local Python setup. If you get every question below right, you can move to the next lesson. None of these activities count toward course progress.

Quick Check

1. If X has six students and two feature columns, what is X.shape?
2. What does X[0, 1] select?
3. Which expression selects all rows of column zero?
4. What is the shape of X.mean(axis=0) if X.shape is (6,2)?

0 of 4 questions answered.

Goal

Create a NumPy array, trace its rows and columns, predict a slice, choose the right axis, and explain a small broadcast and matrix-vector product used by ML code.

Arrays and shape​

A NumPy array is numerical data with a shape. P1 introduced Python lists; np.array(...) converts nested lists into a table of numbers. This is the six-student feature table from L1.2 — Datasets as Tables:

import numpy as np

X = np.array([
[2.0, 0.70],
[5.0, 0.88],
[4.0, 0.82],
[3.0, 0.76],
[6.0, 0.95],
[1.0, 0.60],
])
y = np.array([0, 1, 1, 0, 1, 0])
print(X.shape) # (6, 2)
print(y.shape) # (6,)

Each row is one example. Column zero is study hours and column one is attendance. X.shape == (6, 2) says exactly six rows and two columns. The tuple (6,) represents a one-dimensional six-item target array; it is not the same as a 6-by-1 matrix. X.shape[0] is the number of rows; X.shape[1] is the number of columns.

Predict

If one more student row [7.0, 0.80] is appended to X, what will its shape become?

Slices and shapes​

Python indexes start at zero. For a two-dimensional NumPy array you can give row, column inside one pair of brackets:

print(X[0, 1]) # 0.7: first student's attendance
print(X[0, :]) # [2.0, 0.7]: complete first row
print(X[:, 0]) # [2.0, 5.0, 4.0, 3.0, 6.0, 1.0]
print(X[1:3, :]) # rows 1 and 2 (end 3 excluded)

A colon : means all entries of that dimension. In 1:3, the start is included and the end is excluded. A slice generally returns an array instead of a single number. Checking result.shape makes mistakes easier to find.

When a model expects one example as a two-dimensional batch, X[0:1, :] keeps shape (1, 2), whereas X[0] has shape (2,). The reshape(-1, 1) expression you see in the L1.3 Lab code turns a vector into a one-column matrix; -1 asks NumPy to infer the matching row count.

Axis and broadcasting​

An axis is a direction in the array. For this table:

print(X.mean(axis=0)) # mean of each column: shape (2,)
print(X.mean(axis=1)) # mean of each row: shape (6,)

axis=0 combines values down the rows, keeping one result per column. axis=1 combines values across columns, keeping one result per row. A row mean here mixes hours with attendance, which may be mathematically valid but has no useful shared unit. Always check what the numbers mean, not just that the operation ran.

Broadcasting allows NumPy to apply one smaller array to many rows when shapes are compatible:

column_means = X.mean(axis=0) # shape (2,)
centered = X - column_means # shape (6, 2)
print(centered.shape)

The first column's mean is subtracted from each study-hours entry, and the second column's mean from each attendance entry. The two-element mean vector is applied across six rows; it does not append another row. If the small array had an incompatible size such as (3,), NumPy would raise a shape/broadcasting error rather than silently fixing it.

Array math​

Arithmetic on NumPy arrays works element by element when the shapes fit:

predictions = np.array([3.0, 5.0, 7.0])
targets = np.array([2.0, 4.0, 9.0])
squared_errors = (predictions - targets) ** 2
print(squared_errors) # [1. 1. 4.]

With two same-shaped Python lists, + concatenates; with NumPy arrays, + adds matching elements. That distinction matters in L1.1 when you see squared error and np.mean(...).

The @ operator is matrix multiplication, not elementwise multiplication. A 6-by-2 feature table times a length-2 weights vector produces one weighted score per student:

weights = np.array([2.0, 1.0])
scores = X @ weights
print(scores.shape) # (6,)
print(scores[0]) # 2.0 * 2.0 + 0.70 * 1.0 = 4.7

The inner dimensions must match: (6, 2) @ (2,) is valid; (6, 2) @ (3,) is not. Later neural-network Labs extend this shape reasoning to batches and layers.

Complete the browser TODOs​

Run the starter once. The failed checks identify unfinished expressions, not an environment setup problem. Then replace the placeholder assignments in order: first attendance X[0, 1]; entire study-hours column X[:, 0]; two column means with axis=0; broadcast the mean vector over the table; and calculate weighted scores using @. Predict each output's shape before running. Three progressive hints and the full checked answer are available if you get stuck.

Loading lab…

Spend 10 more minutes changing one thing at a time: switch axis=0 to axis=1 and check the new shape; then reset and change one input row. Explain which results change and why.

Quick Check

1. Why does X[0:1, :] keep two dimensions?
2. What is the shape of (6, 2) @ (2,) ?
3. What does X - X.mean(axis=0) do?

0 of 3 questions answered.

Key Takeaways

  • np.array creates numeric arrays; shape counts dimensions in order.
  • X.shape == (6, 2) means six examples by two features, matching L1.2.
  • Indexing chooses values and slicing chooses ranges; : selects a full dimension.
  • axis=0 aggregates down rows; axis=1 aggregates across columns.
  • Broadcasting repeats compatible smaller shapes; @ performs a dot product or matrix multiplication.

Next: L1.1 — What Machine Learning Is Really Optimizing.