#411Many-to-one — take the last timestepEasy

Many-to-one — take the last timestep

Background

For many-to-one prediction, the RNN reads the whole window and you use only the last timestep's hidden vector — out[:, -1, :] in PyTorch — as the summary to feed the output head:

out:(B,T,H)    out[:,1,:]:(B,H)\text{out}:(B, T, H) \;\longrightarrow\; \text{out}[:, -1, :] : (B, H)

Problem statement

Implement last_timestep(out) returning the last timestep of each sequence in the batch.

Input

  • out — array-like of shape (B, T, H).

Output

Returns an np.ndarray of shape (B, H): the hidden vector at the final timestep for each batch item.

Examples

Example 1

Input:  out = [[[1], [2], [3]]]     # B=1, T=3, H=1
Output: [[3]]

Explanation: the last (T=3) timestep.

Example 2 — batch of 2

Input:  out = [[[1, 1], [2, 2]], [[3, 3], [4, 4]]]   # B=2, T=2, H=2
Output: [[2, 2], [4, 4]]

Constraints

  • Index the time axis at -1, keeping the batch and hidden axes.
  • Return shape (B, H).

Notes

  • For many-to-many tasks you'd keep all timesteps instead; the choice of which outputs to read defines the task shape.
Python
Loading...

▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.

  • Example — single sequence last step
  • Reference — batch of two
  • Sample — picks the final time index