RNN Over a Sequence
Implement rnn_sequence(X, h0, Wh, Wx, b) that processes all time steps and returns the final hidden state.
Examples
T=1 equals single rnn_step
- Input
- rnn_sequence([[1, 0]], [0, 0], [[0, 0], [0, 0]], [[1, 0], [0, 1]], [0, 0])
- Output
- [0.76159, 0]
All-zero sequence: final state = h0 processed T times
- Input
- rnn_sequence([[0], [0], [0]], [0], [[1]], [[1]], [0])
- Output
- [0]
Hints
Hint 1
Use a matrix product rather than nested loops, and check which operand transposes.
Hint 2
Return last rather than all hidden states.
Requirements
X: Input sequence of shape (T, input_size)h0: Initial hidden state, shape (hidden_size,)Wh: Hidden-to-hidden weights, shape (hidden_size, hidden_size)Wx: Input-to-hidden weights, shape (hidden_size, input_size)b: Bias, shape (hidden_size,)Return Final hidden state h_T, shape (hidden_size,).
Constraints
Allowed library: NumPy only
Time limit: 200 ms, Memory: 64 MB
Where this shows up
8 employers weight this skill
3 quant funds, 3 frontier labs, 2 AI product companies. Top match scores 82.
import numpy as np
def rnn_sequence(X: np.ndarray, h0: np.ndarray, Wh: np.ndarray, Wx: np.ndarray, b: np.ndarray) -> np.ndarray:
"""
Run an RNN over a sequence and return the final hidden state.
Args:
X: Input sequence of shape (T, input_size)
h0: Initial hidden state, shape (hidden_size,)
Wh: Hidden-to-hidden weights, shape (hidden_size, hidden_size)
Wx: Input-to-hidden weights, shape (hidden_size, input_size)
b: Bias, shape (hidden_size,)
Returns:
Final hidden state h_T, shape (hidden_size,).
"""
# YOUR CODE HERE
pass