Train an Elman Network One Step at a Time
Elman's simple recurrent network reads a sequence one item per time step. Next to its input units it has context units that hold a copy of the hidden layer from the previous step. Implement one training pass over a sequence with the network's own learning rule.
Implement srn_train(xs, ds, W_xh, W_ch, b_h, W_hy, b_y, lr).
Inputs
xs: list of T input vectors, each of length nin. ds: list of T target vectors, each of length nout.
W_xh (H×nin), W_ch (H×H), b_h (length H): input-to-hidden weights, context-to-hidden weights, hidden bias.
W_hy (nout×H), b_y (length nout): hidden-to-output weights and output bias.
lr: learning rate η≥0.
At every step t=1,…,T, with the logistic function σ(z)=1/(1+e−z):
- Forward: ht=σ(Wxhxt+Wchct+bh) and yt=σ(Whyht+by). Before the first step every context unit is 0.5: c1=(0.5,…,0.5).
- Error: record et=∑k(yt,k−dt,k)2.
- Learn: one gradient step on Et=21∑k(yt,k−dt,k)2 for all five weight arrays, computed with the weights as they were in the forward pass. The context ct is treated as a fixed input: no error is sent back into earlier steps.
- Copy: ct+1=ht (the hidden vector from step 1 of this time step). The copy has weight 1 and is never trained.
Output: a dict with keys "errors" (the T values et), "W_xh", "W_ch", "b_h", "W_hy", "b_y" (the weights after the pass, as nested lists) and "context" (the context after the last copy, i.e. hT). Round every number to 4 decimals.
Notes
- Do not modify the arguments in place.
lr = 0 gives a plain forward pass.