|
| 1 | +""" |
| 2 | +Minimal Recurrent Neural Network (RNN) demonstration. |
| 3 | +
|
| 4 | +Forward propagation explanation: |
| 5 | +https://towardsdatascience.com/forward-propagation-in-neural-networks-simplified-math-and-code-version-bbcfef6f9250 |
| 6 | +RNN fundamentals: |
| 7 | +https://towardsdatascience.com/recurrent-neural-networks-d4642c9bc7ce/ |
| 8 | +""" |
| 9 | + |
| 10 | +import math |
| 11 | +import random |
| 12 | + |
| 13 | + |
| 14 | +def sigmoid_function(value: float, deriv: bool = False) -> float: |
| 15 | + if deriv: |
| 16 | + return value * (1 - value) |
| 17 | + return 1 / (1 + math.exp(-value)) |
| 18 | + |
| 19 | + |
| 20 | +# Initial constants |
| 21 | +INITIAL_VALUE = 0.02 # learning rate |
| 22 | +SEQUENCE_LENGTH = 5 # time steps in the sequence |
| 23 | + |
| 24 | + |
| 25 | +def forward_propagation_rnn(expected: int, number_propagations: int) -> float: |
| 26 | + random.seed(0) |
| 27 | + |
| 28 | + # Random weight initialization |
| 29 | + w_xh = random.random() * 2 - 1 |
| 30 | + w_hh = random.random() * 2 - 1 |
| 31 | + w_hy = random.random() * 2 - 1 |
| 32 | + |
| 33 | + # Training loop |
| 34 | + for _ in range(number_propagations): |
| 35 | + h_prev = 0.0 |
| 36 | + total_error = 0.0 |
| 37 | + |
| 38 | + # Forward pass through time |
| 39 | + for _t in range(SEQUENCE_LENGTH): |
| 40 | + |
| 41 | + x_t = INITIAL_VALUE |
| 42 | + h_t = sigmoid_function(w_xh * x_t + w_hh * h_prev) |
| 43 | + y_t = sigmoid_function(w_hy * h_t) |
| 44 | + error_t = (expected / 100) - y_t |
| 45 | + total_error += abs(error_t) |
| 46 | + |
| 47 | + # Backpropagation Through Time |
| 48 | + d_y = error_t * sigmoid_function(y_t, True) |
| 49 | + d_h = d_y * w_hy * sigmoid_function(h_t, True) |
| 50 | + |
| 51 | + w_hy += INITIAL_VALUE * d_y * h_t |
| 52 | + w_xh += INITIAL_VALUE * d_h * x_t |
| 53 | + w_hh += INITIAL_VALUE * d_h * h_prev |
| 54 | + |
| 55 | + h_prev = h_t |
| 56 | + |
| 57 | + final_output = y_t * 100 |
| 58 | + return final_output |
| 59 | + |
| 60 | + |
| 61 | +if __name__ == "__main__": |
| 62 | + expected = 50 |
| 63 | + number_propagations = 100 |
| 64 | + print(forward_propagation_rnn(expected, number_propagations)) |
0 commit comments