v9.1.1
Menu

Many-to-One Output Selector

mediumPRORecurrent Neural Networks (RNNs)Deep LearningDeep Learning 1

Problem Statement

Select the final relevant output from a batch of variable-length sequences.

Background

In "Many-to-One" architectures (e.g., sentiment analysis), sequences in a batch often have different lengths. We pad shorter sequences but need to extract the hidden state at the last valid timestep for each sequence.

Your Task

Write a function get_final_states(hidden_states, sequence_lengths) that extracts the final hidden state for each sequence in the batch.

Input Format

  • hidden_states: numpy array of shape (batch_size, max_seq_len, hidden_dim)
  • sequence_lengths: list of integers, length of each sequence in the batch

Output Format

Return a numpy array of shape (batch_size, hidden_dim) containing the last valid hidden state for each sequence.

Example

Input
hidden_states shape (2, 3, 4), sequence_lengths = [2, 3]
Output
Shape (2, 4) with hidden_states[0,1,:] and hidden_states[1,2,:]
Reasoning
  • hidden_states is a 2×3×42 \times 3 \times 4 block: 2 sequences, 3 timestep slots each, and a 4-number hidden vector in every slot. Filled with 00 to 2323 in order, sequence 0 holds [0,1,2,3][0,1,2,3], [4,5,6,7][4,5,6,7], [8,9,10,11][8,9,10,11] and sequence 1 holds [12,…,15][12,\dots,15], [16,…,19][16,\dots,19], [20,…,23][20,\dots,23].
  • sequence_lengths = [2, 3] says how many slots are real. Sequence 0 has only 2 real timesteps, so its third slot [8,9,10,11][8,9,10,11] is padding.
  • A sequence of length LL occupies timesteps 0,1,…,L−10, 1, \dots, L-1 (counting from zero), so its last real step is t=L−1t = L - 1: t=1t = 1 for sequence 0 and t=2t = 2 for sequence 1.
  • That picks [4,5,6,7][4, 5, 6, 7] from sequence 0 and [20,21,22,23][20, 21, 22, 23] from sequence 1.
  • The result is a 2×42 \times 4 array: one row per sequence, one column per hidden unit. The time axis disappears because each sequence keeps exactly one timestep.
  • Notice that always taking the final slot would return the padding vector [8,9,10,11][8,9,10,11] for sequence 0, which is exactly the mistake this selector avoids.

Constraints

  • 1 <= batch_size <= 64
  • 1 <= max_seq_len <= 512
  • 1 <= hidden_dim <= 512
  • sequence_lengths[i] >= 1 for all i

Learn this in

More from Deep Learning 1

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.