← All algorithms

Classification / Neural Network / Regression

Recurrent Neural Network, RNN

2023-12-25

RNN is a special application of ANN in the sense that "remembers the sequence of inputs" by adding the output of the previous hidden layer to the next data's hidden layer with weights. Depending on the purpose, various inputs and outputs are configured as follows: for cases like many-to-one, it is used for time series or word completion, one-to-many is used for automatic sentence completion that describes images from images, and many-to-many is used for outputting multiple time series or language translation.

Normally, RNN is represented with a loop as shown on the left below. In the structure depicted on the right below, the output of the hidden layer at time t-1 is independently weighted and added to the nodes of the existing input layer at time t.

In mathematical terms, the basic structure from the input layer to the hidden layer in artificial neural networks is modified as follows.

\(\phi (Xw-b)\rightarrow \phi^{(t)}(Xw+\phi^{(t-1)}\gamma -b)\)

The subscript, t, here represents temporal order, and γ becomes an additional parameter added for the optimization of the RNN, which is multiplied by the output of the previous hidden layer, as shown in the figure below. Ultimately, the entire output layer becomes

\(y'=\phi_v\lbrace V_j\phi_j^{(t)}(X_iw_{ij}+\phi_j^{(t-1)}\gamma _j-b_j)-b_v\rbrace \)

Therefore, all the weights we need to find for RNN are

\(W_{ij},\ b_j,\ V_j,\ b_v,\ \gamma _j\), and

the \(\phi^{(t-1)}\) is called Context node which is the output of the previous hidden layer as indicated in the picture below.

​


  1. Time Series Analysis

First case, we would like to use RNN is to predict today's closing price of "SK Hynix" stock based on the closing prices from the past 9 days. We use last one year of daily stock prices.

(1.1) Structure of RNN

The structure of an RNN is as follows. The input layer consists of 9 nodes, where each X9 represents the price from the previous day, and X1 represents the price from 9 days ago. The hidden layer is composed of 5 nodes, using the Sigmoid activation function. The output layer, used for predicting today's price (i.e., Many-to-one), consists of a single node and employs the RELU activation function.

\(\phi_v \left(x\right)=max(0,X)\) \(\text{if} X \ge 0\)

\(\phi_v = 0\)          else ​

The cost function for optimization is the total sum of the squares of the differences between the actual and predicted values.

\(L=\sum _{\ }^{\ }(X_{10}-\hat X_{10})^2\)

(1.2) Data Preparation and Preprocessing

Time series data was downloaded from quote.yahoo.com by searching for SK Hynix historical data. The entire data was normalized in units of ten thousand and then the daily closing prices of the past ten consecutive days were summarized to create a 10x239 matrix. The following figure represents the actual closing prices. The first 9 rows are used as the input layer, and the last row is used as the output layer to calculate errors.

(1.3) Cell settings for the Weights

The necessary coefficients, Wij, bj, Vj, bv, and γj for RNN are set to the following sizes:

Below table represents the coefficient areas delineated by color for RNN execution.

​

(1.4) Computation

Computation procedure is strictly done in a forward manner following the RNN formulation.

\(y'=\phi_v\lbrace V_j\phi_j^{(t)}(X_iw_{ij}+\phi_j^{(t-1)}\gamma _j-b_j)-b_v\rbrace \)

Here, the initial context node Φ(t-1)j set to 0.

Product of the hidden layer = \(X_iW_{ij}=\text{MMULT}(W_{ij},X_i)\)

Context layer = Output of the previous hidden layer

Product of the context layer = \(\phi_j^{(t-1)}\gamma _j\rightarrow \phi_j^{(t-1)}\odot \gamma _j\), where ⊙ is the Hadamard product, i.e. component-wise product.

Sum of the hidden layer = Product of the Hidden layer + product of the context layer - Bias

\(X_iW_{ij}+\phi_j^{(t-1)}\gamma _j-b_j\)

Output of the hidden layer = Sigmoid of the Sum of the hidden layer, 1/(1+EXP(-Sum of the hidden layer))

\(\phi_j^{(t)}(X_iw_{ij}+\phi_j^{(t-1)}\gamma _j-b_j)\)

Sum of the output layer =

\(V_j\phi_j^{(t)}-b_v=\text{MMULT}(V_j,\phi_j)-b_v\)

Output of the output layer =

\(y' = \phi_v\lbrace \dots \rbrace =\text{IF( Sum of the output layer >0, Sum of the output layer,0)}\)

The error, \(\epsilon = (y'-X_{10})^2\)

The objective function for optimization = \(\sum_{\ }^{\ } \epsilon\)

The structure of Excel after the first operation is as follows. After copying and pasting it to the entire dataset, perform optimization to minimize costs using Solver. Be sure to choose appropriate absolute references for variables within each Excel function to facilitate copying and pasting.

​

(1.5) Solver

Execute the Solver with the following setting:

​

Following plot shows the comparison between the real and predictions before running Solver.

​After running the solver two consecutive times, the prediction shows a good agreement with the real.

​


(2) Text generation

​Similar to using RNN for time series prediction, it is possible to use RNN for the model for the text generation. At this point, the transformer model used in ChatGPT is the dominant player in this area, we still use a simple Seq2Seq model for the educational purposes here.

The problem under consideration is to create a model that predicts the next character when given the input string.

Input StringOutputInput StringOutput
he is aboya he isboy
he is boyaa he boyis
he a isboya is heboy
he a boyisa is boyhe
he boy isaa boy heis
he boy aisa boy ishe
is he aboyboy he isa
is he boyaboy he a is
is a heboyboy is hea
is a boyheboy is a he
is boy heaboy a heis
is boy aheboy a ishe

​Most neural networks cannot handle strings as input data, so they need to be encoded into numeric form. This is referred to as creating a dictionary.

HEISABOY
X11000
X20100
X30010
X40001
Dictionary

​

(2.1) Structure of RNN

RNN for character prediction is structured as follows. Since the encoding is 4 digits, 4 nodes are needed in the input and output layers. In this case, the hidden layer consists of 3 nodes, so there are also 3 Context nodes for managing memory. The aim is to determine the coefficient matrix W and V by using the given input string, for example, 'He is a boy', such that the sequential input data corresponding to 'He is a' produces the output 'boy' (i.e. '0001').

The activation function used in the hidden layer is Sigmoid, and the output layer uses Softmax.

​The total required coefficient matrix is as follows: for the input layer to the hidden layer, wij = [4x3+3]; for the context layer, γj = [3]; for the output layer, Vj = [3x4+4], so a total of 34 coefficients are needed.

The cost for optimization is the sum of the Softmax output values and the Sum Square Error of the output values.

(2.2) Worksheet setup

(2.2.1) Preprocessing

To implement in Excel, first use the dictionary defined above to preprocess and determine the input value as follows.

​

​

(2.2.2) Structure of the weight matrix and initialization

The size of each coefficient matrix is determined as follows, and the RAND function is used to initialize it with random numbers between 0 and 1.

​

(2.3) Computation

Computation is carried out in the forward propagation manner from the input layer to output layer following the RNN formulation:

\(y'=\phi_v\lbrace V_j\phi_j^{(t)}(X_iw_{ij}+\phi_j^{(t-1)}\gamma _j-b_j)-b_v\rbrace \)

The input data is encoded as the vector of size of 4

\(X^{(1)},X^{(2)},X^{(3)}\)

​For the first input data, X(1),

$\phi^{(1)}=\text{sigmoid}(X^{(1)}W+0-b)$

where the first context node Φj is initialized to 0.

For the 2nd, and 3rd input data, X(2), X(3), the weighted output from the previous Hidden layer as the context node is added as follows:

\(\phi^{(2)}=\text{sigmoid}(X^{(2)}W+\phi^{(1)}\gamma -b)\)

\(\phi^{(3)}=\text{sigmoid}(X^{(3)}W+\phi^{(2)}\gamma -b)\)

The sum of the output layer becomes

\(V\phi^{(3)}-b_v\)

and the output of the output layer is expressed as a Softmax function:

\(y_i'=\dfrac{e^{V_{ij}\phi_j^3-b_{v,j}}}{e^{V_{1j}\phi_j^3-b_{v,j}}+e^{V_{2j}\phi_j^3-b_{v,j}}+e^{V_{3j}\phi_j^3-b_{v,j}}+e^{V_{4j}\phi_j^3-b_{v,j}}}\)

The error, \(\epsilon\) of individual data set is defined as:

\(\epsilon=\sum_{i}^{\ }(y'_i-y_i)^2=(y_1'-y_1)^2+(y_2'-y_2)^2+(y_3'-y_3)^2+(y_4'-y_4)^2\)

The objective, J for the optimization is the sum of all the errors

\(J = \sum_{\ }^{\ }\epsilon \)

​The results in Excel worksheet after the first computation is as below. We just need to copy and paste to the rest of the data. Then, lastly run the Solver to find all the coefficients to minimize the objective. 

​

(2.4) Run the Solver

​Set the Solver parameters as below and execute the Solver.

The coefficients output from the Solver makes no mistake in predicting the next character as shown below.

​