v9.1.1
Menu

LSTM Gate Computation

hardPROCNNs & Sequence ModelsMachine Learning 2

Compute the LSTM gates for one timestep.

Given previous hidden state ht−1h_{t-1}, previous cell state ct−1c_{t-1}, and input xtx_t, compute all four gates by concatenating [ht−1,xt][h_{t-1}, x_t] into a combined vector, then:

  • Forget gate: f=σ(Wf⋅[h,x]+bf)f = \sigma(W_f \cdot [h, x] + b_f)
  • Input gate: i=σ(Wi⋅[h,x]+bi)i = \sigma(W_i \cdot [h, x] + b_i)
  • Candidate: c~=tanh⁡(Wc⋅[h,x]+bc)\tilde{c} = \tanh(W_c \cdot [h, x] + b_c)
  • Cell state: ct=f⊙ct−1+i⊙c~c_t = f \odot c_{t-1} + i \odot \tilde{c}
  • Output gate: o=σ(Wo⋅[h,x]+bo)o = \sigma(W_o \cdot [h, x] + b_o)
  • Hidden state: ht=o⊙tanh⁡(ct)h_t = o \odot \tanh(c_t)

Return (h_t, c_t) both as lists rounded to 4 decimal places.

Example

Input
h_prev = [0]
c_prev = [0]
x = [1]
W_f = [[0.5, 0.5]]
b_f = [0]
W_i = [[0.5, 0.5]]
b_i = [0]
W_c = [[0.5, 0.5]]
b_c = [0]
W_o = [[0.5, 0.5]]
b_o = [0]
Output
([0.1743], [0.2876])
Reasoning
  • Inputs: hidden size 1, input size 1. The memory starts empty (ht−1=[0]h_{t-1} = [0], ct−1=[0]c_{t-1} = [0]) and xt=[1]x_t = [1]. Each weight matrix is 1×21 \times 2: one row per hidden unit, one column per entry of [ht−1,xt]=[0,1][h_{t-1}, x_t] = [0, 1]. All biases are 0.
  • Gates: every gate gets the same pre-activation, 0.5⋅0+0.5⋅1+0=0.50.5 \cdot 0 + 0.5 \cdot 1 + 0 = 0.5. So f=i=o=σ(0.5)=11+e−0.5≈0.6225f = i = o = \sigma(0.5) = \frac{1}{1 + e^{-0.5}} \approx 0.6225, and the candidate is c~=tanh⁡0.5≈0.4621\tilde{c} = \tanh 0.5 \approx 0.4621.
  • Cell state: ct=0.6225⋅0+0.6225⋅0.4621≈0.2876c_t = 0.6225 \cdot 0 + 0.6225 \cdot 0.4621 \approx 0.2876. The old cell was empty, so all of the memory comes from the candidate.
  • Hidden state: tanh⁡0.2876≈0.2800\tanh 0.2876 \approx 0.2800, so ht=0.6225⋅0.2800≈0.1743h_t = 0.6225 \cdot 0.2800 \approx 0.1743.
  • Output: ([0.1743], [0.2876]), two lists of length hidden_size, hth_t first. Since o∈(0,1)o \in (0, 1), ∣ht∣≤∣tanh⁡ct∣|h_t| \le |\tanh c_t|, with equality only when ct=0c_t = 0. Round only at the end: multiplying the rounded 0.6225 and 0.4621 gives 0.2877.

Constraints

  • h_prev, c_prev: 1D lists (hidden_size)
  • x: 1D list (input_size)
  • W_f, W_i, W_c, W_o: 2D lists (hidden_size x (hidden_size + input_size))
  • b_f, b_i, b_c, b_o: 1D lists (hidden_size)
  • Return tuple (h_t, c_t) rounded to 4 decimal places

Learn this in

More from Machine Learning 2

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.