Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
One of the most essential concepts in multi-dimensional computing is understanding how aggregation functions operate across specific axes.
Whether you are computing the average grade per student, the total sales per store across quarters, or normalizing batch activations in a convolutional neural network, mastering the axis and keepdims parameters is non-negotiable.
axis ParameterA common misconception is thinking of axis as "operating along a dimension". A far clearer and more intuitive mental model is:
axis parameter specifies the dimension that is COLLAPSED (eliminated) during the aggregation.Consider a 2D matrix of shape (rows, cols) = (4, 3):
axis=0 (Rows collapsed): Collapses row-by-row down the columns. The row dimension disappears. Output shape is (3,) (one result per column).axis=1 (Columns collapsed): Collapses column-by-column across the rows. The column dimension disappears. Output shape is (4,) (one result per row).axis=None (Default): Collapses all dimensions, flattening the array into a single scalar value.The exact same rule holds for higher dimensions. If you have an array of shape (Batch, Height, Width, Channels) = (32, 28, 28, 3):
np.mean(tensor, axis=0) collapses the batch axis $\implies$ shape becomes (28, 28, 3).np.mean(tensor, axis=(1, 2)) collapses spatial height and width $\implies$ shape becomes (32, 3).np.mean(tensor, axis=-1) collapses the color channels $\implies$ shape becomes (32, 28, 28).keepdims=True for BroadcastingWhen you compute an axis reduction, NumPy collapses that dimension, dropping the rank by 1. For example, in a $(4, 3)$ matrix, grades.mean(axis=1) produces shape (4,) rather than (4, 1).
If you immediately try to subtract this mean from the original matrix to center the data: grades - student_averages NumPy attempts to align trailing dimensions: $(4, 3)$ with $(4,)$, which fails with a broadcasting ValueError!
Setting keepdims=True preserves the collapsed dimension as a singleton axis of length 1:
Output:
You can collapse multiple axes simultaneously by passing a tuple of integers:
np.sum(arr, axis=0) for an array of shape (10, 20)?(N, M), which axis parameter computes row-wise sums (the sum across columns for each row)?keepdims=True do during an aggregation operation?x has shape (4, 6) and you execute x - np.mean(x, axis=1), why does it raise a broadcasting ValueError?np.mean(arr, axis=(0, 2)) to an array arr of shape (5, 8, 12)?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Test your understanding of this lesson with 5 questions. Each question has one correct answer.