v9.1.1
Menu

RNN Single Step Forward

mediumFREERecurrent Neural Networks (RNNs)Deep LearningDeep Learning 1

Problem Statement

Compute the hidden state for a single timestep in a standard RNN.

Background

The update rule for a vanilla RNN is:

at=tanh⁡(Waa⋅at−1+Wax⋅xt+ba)a_t = \tanh(W_{aa} \cdot a_{t-1} + W_{ax} \cdot x_t + b_a)

Where:

  • ata_t is the new hidden state
  • at−1a_{t-1} is the previous hidden state
  • xtx_t is the input at timestep tt
  • WaaW_{aa} is the hidden-to-hidden weight matrix
  • WaxW_{ax} is the input-to-hidden weight matrix
  • bab_a is the bias vector

Your Task

Write a function rnn_step(prev_hidden, input_vec, W_aa, W_ax, b_a) that computes and returns the new hidden state using np.tanh.

Input Format

  • prev_hidden: numpy array of shape (hidden_dim,)
  • input_vec: numpy array of shape (input_dim,)
  • W_aa: numpy array of shape (hidden_dim, hidden_dim)
  • W_ax: numpy array of shape (hidden_dim, input_dim)
  • b_a: numpy array of shape (hidden_dim,)

Output Format

Return a numpy array of shape (hidden_dim,) representing the new hidden state.

Example

Input
prev_hidden=[0,0], input_vec=[1,2], W_aa=[[0.1,0.2],[0.3,0.4]], W_ax=[[0.5,0.6],[0.7,0.8]], b_a=[0,0]
Output
[0.9354, 0.9801] (approximately)
Reasoning
  • Inputs: the previous hidden state at−1=[0,0]a_{t-1} = [0, 0] (2 hidden units), the current input xt=[1,2]x_t = [1, 2] (2 features), two 2×22 \times 2 weight matrices and a zero bias. Each row of a weight matrix belongs to one hidden unit.
  • Recurrent term: Waaat−1W_{aa} a_{t-1} multiplies every weight by 00, so it is [0,0][0, 0]. At the first timestep there is no memory yet.
  • Input term: row 1 of WaxW_{ax} gives 0.5⋅1+0.6⋅2=1.70.5 \cdot 1 + 0.6 \cdot 2 = 1.7; row 2 gives 0.7⋅1+0.8⋅2=2.30.7 \cdot 1 + 0.8 \cdot 2 = 2.3.
  • Pre-activation: add the two terms and ba=[0,0]b_a = [0, 0] to get [1.7,2.3][1.7, 2.3].
  • Squash: applying tanh⁡\tanh to each entry turns 1.71.7 into ≈0.9354\approx 0.9354 and 2.32.3 into ≈0.9801\approx 0.9801, giving [0.9354, 0.9801], a vector with one value per hidden unit.
  • Notice that both values sit close to 11: tanh⁡\tanh maps any real number into (−1,1)(-1, 1) and saturates for large inputs, so the second unit's larger pre-activation gains only a little.

Constraints

  • All inputs are valid numpy arrays with compatible dimensions
  • hidden_dim and input_dim are between 1 and 512

Learn this in

More from Deep Learning 1

solution.py

Test results

Sign in to run your code against the test cases.