Typorithm · easy

Reductions, axes and keepdims

pythonnumpynumerical-computingindependent-practice
Saved on this device
Full lesson · 4 learning steps Open any exercise for focused practice
1

Step 1 of 4 · intro card

Reductions, axes and keepdims

0%

Concept and contract

Reduce the intended population while retaining the dimensions needed by the next operation.

A reduction combines multiple elements into a smaller result. With axis=0 on a matrix, rows are combined and one result remains per column. With axis=1, columns are combined and one result remains per row. Omitting axis combines all coordinates. These are different populations even when their grand totals agree. Keepdims preserves reduced axes as dimensions of length one, making the intended later broadcast visible.

The worked example returns column totals as a one-row float64 matrix. This convention makes an aggregate shaped (1, features) explicit. It does not claim that a one-dimensional summary is wrong; the chosen output shape is part of this function interface and is tested accordingly.

Mechanism and worked example

The function validates a finite, non-empty matrix and calls sum(axis=0, keepdims=True).

The function validates a finite, non-empty matrix and calls sum(axis=0, keepdims=True). For three observations with two features, it returns one row and two columns. Trace the additions for each column independently before running the code. A single-column input is included so that the difference between column totals and the number of observations remains visible.

Reductions have operation-specific rules. Sum has an additive identity for empty input, while a mean of an empty population has no observed denominator. This lesson rejects empty matrices at its boundary rather than presenting every reduction as having the same empty-data behavior.

Complete worked example

python

import numpy as np

def inspect_example(rows):
    data = np.asarray(rows, dtype=np.float64)
    if data.ndim != 2 or 0 in data.shape or not np.isfinite(data).all():
        raise ValueError("expected a non-empty finite matrix")
    return data.sum(axis=0, keepdims=True)
Reasoning
The function validates a finite, non-empty matrix and calls sum(axis=0, keepdims=True). For three observations with two features, it returns one row and two columns. Trace the additions for each column independently before running the code. A single-column input is included so that the difference between column totals and the number of observations remains visible. Reductions have operation-specific rules. Sum has an additive identity for empty input, while a mean of an empty population has no observed denominator. This lesson rejects empty matrices at its boundary rather than presenting every reduction as having the same empty-data behavior.
Open in local Python playground ↗

Focused decision: context is in the complete example

python

column_totals = data.sum(axis=0, keepdims=True)
row_totals = data.sum(axis=1, keepdims=True)
Focused decision
Type this short numerical decision after reading its complete context. The complete imports, array construction, validation, and result checks remain in the worked example. Typing records practice; only the downloadable computer lab executes Python.

Counterexamples and common mistakes

The controlled mistake computes a grand total and reshapes it to one-by-one.

The controlled mistake computes a grand total and reshapes it to one-by-one. It can look sensible in a dashboard because the displayed number is a valid sum, but it no longer answers the per-feature question. A second error is dividing an already filtered sum by the unfiltered row count when computing a mean. The denominator must describe the same selected observations as the numerator.

Keepdims does not remember business meaning or repair an incorrect axis. It only retains dimensions. Always state which observations are combined and which identifiers remain aligned to the output. Wider integer accumulators and floating-point rounding also need their own explicit reasoning.

Controlled mistake: inspect the failing numerical contract

python

import numpy as np

def inspect_example(rows):
    data = np.asarray(rows, dtype=np.float64)
    if data.ndim != 2 or 0 in data.shape or not np.isfinite(data).all():
        raise ValueError("expected a non-empty finite matrix")
    return np.asarray([[data.sum()]], dtype=np.float64)
Reasoning
The controlled mistake computes a grand total and reshapes it to one-by-one. It can look sensible in a dashboard because the displayed number is a valid sum, but it no longer answers the per-feature question. A second error is dividing an already filtered sum by the unfiltered row count when computing a mean. The denominator must describe the same selected observations as the numerator. Keepdims does not remember business meaning or repair an incorrect axis. It only retains dimensions. Always state which observations are combined and which identifiers remain aligned to the output. Wider integer accumulators and floating-point rounding also need their own explicit reasoning.
Open in local Python playground ↗

Independent practice

Change the output to one total per observation, stored as a column matrix.

Change the output to one total per observation, stored as a column matrix. Keep finite-value validation and preserve every observation in order. This is one axis-choice task; do not flatten first, sort the values or drop rows that happen to have a zero total.

Draw a three-by-two input and its three-by-one expected result. A second fixture with two rows and one column should preserve those two individual values. That fixture makes a grand-total implementation fail even when the first example contains repeated numbers.

Step 1: Return one row total per observation as a column matrix. Step 2: Retain the working imports, input validation and array shapes. Change the stated policy, run the supplied practice cases, then explain the newly accepted or rejected boundary.

Practice starter: solve before reading the solution

python

import numpy as np

def inspect_example(rows):
    data = np.asarray(rows, dtype=np.float64)
    if data.ndim != 2 or 0 in data.shape or not np.isfinite(data).all():
        raise ValueError("expected a non-empty finite matrix")
    return data.sum(axis=0, keepdims=True)

# Independent task: Return one row total per observation as a column matrix.
Reasoning
Return one row total per observation as a column matrix.
Open in local Python playground ↗
  • Hint 1: Each row must produce one retained value.
  • Hint 2: Use axis=1 and keep the singleton column dimension.

Solution, tests and trade-offs

The practice solution changes axis=0 to axis=1 and keeps keepdims=True.

The practice solution changes axis=0 to axis=1 and keeps keepdims=True. Its output shape is therefore (observations, 1). The lab checks the exact dimensions and values, including a matrix with a negative measurement and a row total of zero. A sum of zero is a valid result and is not equivalent to an empty population.

Discuss whether an aggregate should remain two-dimensional based on its consumer. A plotting API might accept a vector, while a later feature-aligned expression benefits from a retained singleton dimension. The course deliberately tests this boundary instead of accepting every shape with the same element count.

Practice solution and acceptance checks

python

import numpy as np

def inspect_example(rows):
    data = np.asarray(rows, dtype=np.float64)
    if data.ndim != 2 or 0 in data.shape or not np.isfinite(data).all():
        raise ValueError("expected a non-empty finite matrix")
    return data.sum(axis=1, keepdims=True)
Reasoning
The practice solution changes axis=0 to axis=1 and keeps keepdims=True. Its output shape is therefore (observations, 1). The lab checks the exact dimensions and values, including a matrix with a negative measurement and a row total of zero. A sum of zero is a valid result and is not equivalent to an empty population. Discuss whether an aggregate should remain two-dimensional based on its consumer. A plotting API might accept a vector, while a later feature-aligned expression benefits from a retained singleton dimension. The course deliberately tests this boundary instead of accepting every shape with the same element count.
Open in local Python playground ↗

Interview reasoning and next step

Explain axis=0, axis=1, axis=None and keepdims using the same rectangular matrix.

Explain axis=0, axis=1, axis=None and keepdims using the same rectangular matrix. Then explain why an empty mean is not simply a sum with a different name. If the problem asks for a percentage, identify its population and units before selecting an axis or dividing.

Type the compact reduction and predict its shape from memory. App questions use concrete coordinates and output dimensions. Next, handle missing and non-finite measurements explicitly so a numerical summary does not silently invent observations or produce an unusable infinite result.

Optional stretch — after the core task works: Add one independently reasoned boundary case and explain its expected value before running it.

Computer practice: https://applydjinn.com/typorithm/numpy-lab-20261106.zip. Install pinned dependencies in an isolated Python environment. Run verify.py, then change the working exercise baseline and run --practice np-reductions. The real NumPy arrays, numerical contracts, random state checks and temporary numeric files use owned fixtures only. No production database, feed, account or paid service is used. This lab executes Python; the PC typing trainer and native reading progress do not execute it.

Reduce the intended population while retaining the dimensions needed by the next operation.