We can't find the internet
Attempting to reconnect
Something went wrong!
Attempting to reconnect
Cumulative Sum
A cumulative sum keeps a running total. At each position, include the current value and every value before it.
Your task
Implement cumulative_sum(x) for a floating-point vector of shape (n,).
Return a vector of the same shape, dtype and device, leaving x unchanged.
output[i] = x[0] + x[1] + ... + x[i]
For [5, 0, -3, 2], return [5, 5, 2, 4]:
- Start with 5.
- Adding 0 keeps the total at 5.
- Adding -3 reduces it to 2.
- Adding 2 brings it to 4.
Negative inputs can make the running total decrease. Do not sort the input, replace negative values or return only the final total.
This is an inclusive cumulative sum: the first output is x[0], not zero.
A one-element input is unchanged in value; an empty input returns shape (0,).
For a nonempty input, the last result is the sum of the whole vector, subject
to floating-point rounding.
Use torch.cumsum(x, dim=0) or jnp.cumsum(x, axis=0). Unlike a sum reduction,
this operation keeps one output for every input position.
Understand the ideas behind this exercise. The Problem tab contains the exact implementation requirements.
Give each tensor axis a meaning
A tensor's shape tells you how many entries each axis has. It does not tell you
what those entries represent. For example, (batch, features) and
(features, batch) use different axis orders. Name the axes before choosing an
operation.
A reduction combines entries along an axis, for example by summing or
averaging. Averaging the features of a (B, D) tensor gives one number per
example, with shape (B,). Keeping the reduced axis gives shape (B, 1) instead.
For [[2, 4, 6], [1, 3, 5]], the row means with the axis kept are [[4], [3]].
Subtracting them from the input gives [[-2, 0, 2], [-2, 0, 2]]: each row has
been centered using its own mean.
Reshape and transpose do different jobs
A reshape regroups elements using the operation's traversal order. A transpose
changes the axis order. For the usual row-major reshape, [[1, 2, 3], [4, 5, 6]]
reshaped to (3, 2) becomes [[1, 2], [3, 4], [5, 6]]. Transposing the original
instead gives [[1, 4], [2, 5], [3, 6]].
Both results have shape (3, 2), but their entries mean different things. Check
values as well as shapes. Unequal axis sizes make many axis mistakes easier to
spot than square examples do.
Concatenate along an axis or stack on a new one
Concatenation extends an existing axis. Stacking creates a new axis. For two
arrays of shape (2, 3), concatenating on axis zero gives (4, 3). Stacking on
a new leading axis gives (2, 2, 3).
Your code, saved here
Sign in to access your accepted solutions and saved draft history. You can keep reading the lesson without an account.
Sign in to your accountStuck?
JAX reference solution
Sign in to track your attempts toward unlocking the reference solution.