<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Neural Net on R Views</title>
    <link>https://rviews.rstudio.com/tags/neural-net/</link>
    <description>Recent content in Neural Net on R Views</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Mon, 20 Jul 2020 00:00:00 +0000</lastBuildDate>
    <atom:link href="https://rviews.rstudio.com/tags/neural-net/" rel="self" type="application/rss+xml" />
    
    
    
    
    <item>
      <title>Building A Neural Net from Scratch Using R - Part 1</title>
      <link>https://rviews.rstudio.com/2020/07/20/shallow-neural-net-from-scratch-using-r-part-1/</link>
      <pubDate>Mon, 20 Jul 2020 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2020/07/20/shallow-neural-net-from-scratch-using-r-part-1/</guid>
      <description>
        


&lt;p&gt;&lt;em&gt;Akshaj is a budding deep learning researcher who loves to work with R. He has worked as a Research Associate at the Indian Institute of Science and as a Data Scientist at KPMG India.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;A lot of deep learning frameworks often abstract away the mechanics behind training a neural network. While this has the advantage of quickly building deep learning models, it has the disadvantage of hiding the details. It is equally important to slow down and understand how neural nets work. In this two-part series, we’ll dig deep and build our own neural net from scratch. This will help us understand, at a basic level, how those big frameworks work. The network we’ll build will contain a single hidden layer and perform binary classification using a vectorized implementation of backpropagation, all written in base-R. We will describe in detail what a single-layer neural network is, how it works, and the equations used to describe it. We will see what kind of data preparation is required to be able to use it with a neural network. Then, we will implement a neural-net step-by-step from scratch and examine the output at each step. Finally, to see how our neural-net fares, we will describe a few metrics used for classification problems and use them.&lt;/p&gt;
&lt;p&gt;In this first part, we’ll present the dataset we are going to use, the pre-processing involved, the train-test split, and describe in detail the architecture of the model. Then we’ll build our neural net chunk-by-chunk. It will involve writing functions for initializing parameters and running forward propagation.&lt;/p&gt;
&lt;p&gt;In the second part, we’ll implement backpropagation by writing functions to calculate gradients and update the weights. Finally, we’ll make predictions on the test data and see how accurate our model is using metrics such as &lt;code&gt;Accuracy&lt;/code&gt;, &lt;code&gt;Recall&lt;/code&gt;, &lt;code&gt;Precision&lt;/code&gt;, and &lt;code&gt;F1-score&lt;/code&gt;. We’ll compare our neural net with a logistic regression model and visualize the difference in the decision boundaries produced by these models.&lt;/p&gt;
&lt;p&gt;By the end of this series, you should have a deeper understanding of the math behind neural-networks and the ability to implement it yourself from scratch!&lt;/p&gt;
&lt;div id=&#34;set-seed&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Set Seed&lt;/h3&gt;
&lt;p&gt;Before we start, let’s set a seed value to ensure reproducibility of the results.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;set.seed(69)&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;architecture-definition&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Architecture Definition&lt;/h3&gt;
&lt;p&gt;To understand the matrix multiplications better and keep the numbers digestible, we will describe a very simple 3-layer neural net i.e. a neural net with a single hidden layer. The &lt;span class=&#34;math inline&#34;&gt;\(1^{st}\)&lt;/span&gt; layer will take in the inputs and the &lt;span class=&#34;math inline&#34;&gt;\(3^{rd}\)&lt;/span&gt; layer will spit out an output.&lt;/p&gt;
&lt;p&gt;The input layer will have two (input) neurons, the hidden layer four (hidden) neurons, and the output layer one (output) neuron.&lt;/p&gt;
&lt;p&gt;Our input layer has two neurons because we’ll be passing two features (columns of a dataframe) as the input. A single output neuron because we’re performing binary classification. This means two output classes - 0 and 1. Our output will actually be a probability (a number that lies between 0 and 1). We’ll define a threshold for rounding off this probability to 0 or 1. For instance, this threshold can be 0.5.&lt;/p&gt;
&lt;p&gt;In a deep neural net, multiple hidden layers are stacked together (hence the name “deep”). Each hidden layer can contain any number of neurons you want.&lt;/p&gt;
&lt;p&gt;In this series, we’re implementing a single-layer neural net which, as the name suggests, contains a single hidden layer.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;n_x&lt;/code&gt;: the size of the input layer (set this to 2).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;n_h&lt;/code&gt;: the size of the hidden layer (set this to 4).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;n_y&lt;/code&gt;: the size of the output layer (set this to 1).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&#34;single_layer_nn.png&#34; alt = &#34;Figure 1: Single layer NNet Architecture. Credits: deep learning.a&#34; height = &#34;400&#34; width=&#34;600&#34;&gt;&lt;/p&gt;
&lt;p&gt;Neural networks flow from left to right, i.e. input to output. In the above example, we have two features (two columns from the input dataframe) that arrive at the input neurons from the first-row of the input dataframe. These two numbers are then multiplied by a set of weights (randomly initialized at first and later optimized).&lt;/p&gt;
&lt;p&gt;An activation function is then applied on the result of this multiplication. This new set of numbers becomes the neurons in our hidden layer. These neurons are again multiplied by another set of weights (randomly initialized) with an activation function applied to this result. The final result we obtain is a single number. This is the prediction of our neural-net. It’s a number that lies between 0 and 1.&lt;/p&gt;
&lt;p&gt;Once we have a prediction, we then compare it to the true output. To optimize the weights in order to make our predictions more accurate (because right now our input is being multiplied by random weights to give a random prediction), we need to first calculate how far off is our prediction from the actual value. Once we have this &lt;em&gt;loss&lt;/em&gt;, we calculate the gradients with respect to each weight.&lt;/p&gt;
&lt;p&gt;The gradients tell us the amount by which we need to increase or decrease each weight parameter in order to minimize the loss. All the weights in the network are updated as we repeat the entire process with the second input sample (second row).&lt;/p&gt;
&lt;p&gt;After all the input samples have been used to optimize weights, we say that one epoch has passed. We repeat this process for multiple number of epochs till our loss stops decreasing.&lt;/p&gt;
&lt;p&gt;At this point, you might be wondering what an activation function is. An activation function adds non-linearity to our network and enables it to learn complex features. If you look closely, a neural network consists of a bunch multiplications and additions. It’s linear and we know that a linear classification model will not be able to learn complex features in high dimensions.&lt;/p&gt;
&lt;p&gt;Here are a few popular activation functions -&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;activation_functions.png&#34; alt = &#34;Figure 2: Sigmoid Activation Function. Credits - analyticsindiamag&#34; height = &#34;400&#34; width=&#34;600&#34;&gt;&lt;/p&gt;
&lt;p&gt;We will use &lt;code&gt;tanh()&lt;/code&gt; and &lt;code&gt;sigmoid()&lt;/code&gt; activation functions in our neural net. Because &lt;code&gt;tanh()&lt;/code&gt; is already available in base-R, we will implement the &lt;code&gt;sigmoid()&lt;/code&gt; function ourselves later on.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;dry-run&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Dry Run&lt;/h3&gt;
&lt;p&gt;For now, let’s see how the numbers flow through the above described neural-net by writing out the equations for a single sample (one input row).&lt;/p&gt;
&lt;p&gt;For one input sample &lt;span class=&#34;math inline&#34;&gt;\(x^{(i)}\)&lt;/span&gt; where &lt;span class=&#34;math inline&#34;&gt;\(i\)&lt;/span&gt; is the row-number:&lt;/p&gt;
&lt;p&gt;First, we calculate the output &lt;span class=&#34;math inline&#34;&gt;\(Z\)&lt;/span&gt; from the input &lt;span class=&#34;math inline&#34;&gt;\(x\)&lt;/span&gt;. We will tune the parameters &lt;span class=&#34;math inline&#34;&gt;\(W\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(b\)&lt;/span&gt;. Here, the superscript in square brackets tell us the layer number and the one in parenthesis tell use the neuron number. For instance &lt;span class=&#34;math inline&#34;&gt;\(z^{[1] (i)}\)&lt;/span&gt; is the output from the &lt;span class=&#34;math inline&#34;&gt;\(i^{{th}}\)&lt;/span&gt; neuron of the &lt;span class=&#34;math inline&#34;&gt;\(1^{{st}}\)&lt;/span&gt; layer.&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[z^{[1] (i)} = W^{[1]} x^{(i)} + b^{[1] (i)}\tag{1}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Then we’ll pass this value through the &lt;code&gt;tanh()&lt;/code&gt; activation function to get &lt;span class=&#34;math inline&#34;&gt;\(a\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[a^{[1] (i)} = \tanh(z^{[1] (i)})\tag{2}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;After that, we’ll calculate the value for the final output layer using the hidden layer values.&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[z^{[2] (i)} = W^{[2]} a^{[1] (i)} + b^{[2] (i)}\tag{3}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Finally, we’ll pass this value through the &lt;code&gt;sigmoid()&lt;/code&gt; activation function and obtain our output probability.
&lt;span class=&#34;math display&#34;&gt;\[\hat{y}^{(i)} = a^{[2] (i)} = \sigma(z^{ [2] (i)})\tag{4}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;To obtain our prediction class from output probabilities, we round off the values as follows.
&lt;span class=&#34;math display&#34;&gt;\[y^{(i)}_{prediction} = \begin{cases} 1 &amp;amp; \mbox{if } a^{[2](i)} &amp;gt; 0.5 \\ 0 &amp;amp; \mbox{otherwise } \end{cases}\tag{5}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Once, we have the prediction probabilities, we’ll compute the loss in order to tune our parameters (&lt;span class=&#34;math inline&#34;&gt;\(w\)&lt;/span&gt; and &lt;span class=&#34;math inline&#34;&gt;\(b\)&lt;/span&gt; can be adjusted using gradient-descent).&lt;/p&gt;
&lt;p&gt;Given the predictions on all the examples, we will compute the cost &lt;span class=&#34;math inline&#34;&gt;\(J\)&lt;/span&gt; the cross-entropy loss as follows:&lt;br /&gt;
&lt;span class=&#34;math display&#34;&gt;\[J = - \frac{1}{m} \sum\limits_{i = 0}^{m} \large\left(\small y^{(i)}\log\left(\hat{y}^{(i)}\right) + (1-y^{(i)})\log\left(1- \hat{y}^{ (i)}\right) \large \right) \small \tag{6}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Once we have our loss, we need to calculate the gradients. I’ve calculated them for you so you don’t differentiate anything. We’ll directly use these values -&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(dZ^{[2]} = A^{[2]} - Y\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(dW^{[2]} = \frac{1}{m} dZ^{[2]}A^{[1]^T}\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(db^{[2]} = \frac{1}{m}\sum dZ^{[2]}\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(dZ^{[1]} = W^{[2]^T} * g^{[1]&amp;#39;} Z^{[1]}\)&lt;/span&gt; where &lt;span class=&#34;math inline&#34;&gt;\(g\)&lt;/span&gt; is the activation function.&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(dW^{[1]} = \frac{1}{m}dZ^{[1]}X^{T}\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(db^{[1]} = \frac{1}{m}\sum dZ^{[1]}\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Now that we have the gradients, we will update the weights. We’ll multiply these gradients with a number known as the &lt;code&gt;learning rate&lt;/code&gt;. The learning rate is represented by &lt;span class=&#34;math inline&#34;&gt;\(\alpha\)&lt;/span&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(W^{[2]} = W^{[2]} - \alpha * dW^{[2]}\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(b^{[2]} = b^{[2]} - \alpha * db^{[2]}\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(W^{[1]} = W^{[1]} - \alpha * dW^{[1]}\)&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&#34;math inline&#34;&gt;\(b^{[1]} = b^{[1]} - \alpha * db^{[1]}\)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This process is repeated multiple times until our model converges i.e. we have learned a good set of weights that fit our data well.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;load-and-visualize-the-data&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Load and Visualize the Data&lt;/h2&gt;
&lt;p&gt;Since, the goal of the series is to understand how neural-networks work behind the scene, we’ll use a small dataset so that our focus is on building our neural net.&lt;/p&gt;
&lt;p&gt;We’ll use a planar dataset that looks like a flower. The output classes cannot be separated accurately using a straight line.&lt;/p&gt;
&lt;div id=&#34;construct-dataset&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Construct Dataset&lt;/h3&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;df &amp;lt;- read.csv(file = &amp;quot;planar_flower.csv&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let’s shuffle our dataset so that our model is invariant to the order of samples. This is good for generalization and will help increase performance on unseen (test) data.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;df &amp;lt;- df[sample(nrow(df)), ]

head(df)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##           x1        x2 y
## 209  1.53856  3.242555 0
## 347 -0.05617 -0.808464 0
## 386 -3.85811  1.423514 1
## 112  0.82630  0.044276 1
## 104  0.31350  0.004274 1
## 111  2.28420  0.352476 1&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;visualize-data&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Visualize Data&lt;/h3&gt;
&lt;p&gt;We have four hundred samples where two hundred belong each class.&lt;/p&gt;
&lt;p&gt;Here’s a scatter plot between our input variables. As you can see, the output classes are &lt;strong&gt;not&lt;/strong&gt; easily separable.
&lt;img src=&#34;/post/2020-07-11-shallow-neural-net-from-scratch-using-r-part-1/index_files/figure-html/unnamed-chunk-4-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;train-test-split&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Train-Test Split&lt;/h3&gt;
&lt;p&gt;Now that we have our dataset prepared, let’s go ahead and split it into train and test sets. We’ll put 80% of our data into our train set and the remaining 20% into our test set. (To keep the focus on the neural-net, we will not be using a validation set here. ).&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;train_test_split_index &amp;lt;- 0.8 * nrow(df)&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;train-and-test-dataset&#34; class=&#34;section level4&#34;&gt;
&lt;h4&gt;Train and Test Dataset&lt;/h4&gt;
&lt;p&gt;Because we’ve already shuffled the dataset above, we can go ahead and extract the first 80% rows into train set.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;train &amp;lt;- df[1:train_test_split_index,]
head(train)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##           x1        x2 y
## 209  1.53856  3.242555 0
## 347 -0.05617 -0.808464 0
## 386 -3.85811  1.423514 1
## 112  0.82630  0.044276 1
## 104  0.31350  0.004274 1
## 111  2.28420  0.352476 1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Next, we select last 20% rows of the shuffled dataset to be our test set.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;test &amp;lt;- df[(train_test_split_index+1): nrow(df),]
head(test)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##          x1       x2 y
## 210 -0.0352 -0.03489 0
## 348  2.7257 -0.54170 0
## 19  -2.2235  0.42137 1
## 362  2.3366 -0.40412 0
## 143 -1.4984  3.55267 0
## 4   -3.2264 -0.81648 0&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here, we visualize the number of samples per class in our train and test data sets to ensure that there isn’t a major class imbalance.
&lt;img src=&#34;/post/2020-07-11-shallow-neural-net-from-scratch-using-r-part-1/index_files/figure-html/unnamed-chunk-11-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;preprocess&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Preprocess&lt;/h2&gt;
&lt;p&gt;Neural networks work best when the input values are standardized. So, we’ll scale all the values to to have their &lt;code&gt;mean=0&lt;/code&gt; and &lt;code&gt;standard-deviation=1&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Standardizing input values speeds up the training and ensures faster convergence.&lt;/p&gt;
&lt;p&gt;To standardize the input values, we’ll use the &lt;code&gt;scale()&lt;/code&gt; function in R. Note that we’re standardizing the input values (X) only and not the output values (y).&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;X_train &amp;lt;- scale(train[, c(1:2)])

y_train &amp;lt;- train$y
dim(y_train) &amp;lt;- c(length(y_train), 1) # add extra dimension to vector

X_test &amp;lt;- scale(test[, c(1:2)])

y_test &amp;lt;- test$y
dim(y_test) &amp;lt;- c(length(y_test), 1) # add extra dimension to vector&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output below tells us the shape and size of our input data.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;## Shape of X_train (row, column): 
##  320 2 
## Shape of y_train (row, column) : 
##  320 1 
## Number of training samples: 
##  320 
## Shape of X_test (row, column): 
##  80 2 
## Shape of y_test (row, column) : 
##  80 1 
## Number of testing samples: 
##  80&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Because neural nets are made up of a bunch matrix multiplications, let’s convert our input and output to matrices from dataframes. While dataframes are a good way to represent data in a tabular form, we choose to convert to a matrix type because matrices are smaller than an equivalent dataframe and often speed up the computations.&lt;/p&gt;
&lt;p&gt;We will also change the shape of &lt;code&gt;X&lt;/code&gt; and &lt;code&gt;y&lt;/code&gt; by taking its transpose. This will make the matrix calculations slightly more intuitive as we’ll see in the second part. There’s really no difference though. Some of you might find this way better, while others might prefer the non-transposed way. I feel this this makes more sense.&lt;/p&gt;
&lt;p&gt;We’re going to use the &lt;code&gt;as.matrix()&lt;/code&gt; method to construct out matrix. We’ll fill out matrix row-by-row.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;X_train &amp;lt;- as.matrix(X_train, byrow=TRUE)
X_train &amp;lt;- t(X_train)
y_train &amp;lt;- as.matrix(y_train, byrow=TRUE)
y_train &amp;lt;- t(y_train)

X_test &amp;lt;- as.matrix(X_test, byrow=TRUE)
X_test &amp;lt;- t(X_test)
y_test &amp;lt;- as.matrix(y_test, byrow=TRUE)
y_test &amp;lt;- t(y_test)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here are the shapes of our matrices after taking the transpose.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;## Shape of X_train: 
##  2 320 
## Shape of y_train: 
##  1 320 
## Shape of X_test: 
##  2 80 
## Shape of y_test: 
##  1 80&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;build-a-neural-net&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Build a neural-net&lt;/h2&gt;
&lt;p&gt;Now that we’re done processing our data, let’s move on to building our neural net. As discussed above, we will broadly follow the steps outlined below.&lt;/p&gt;
&lt;ol style=&#34;list-style-type: decimal&#34;&gt;
&lt;li&gt;Define the neural net architecture.&lt;/li&gt;
&lt;li&gt;Initialize the model’s parameters from a random-uniform distribution.&lt;/li&gt;
&lt;li&gt;Loop:
&lt;ul&gt;
&lt;li&gt;Implement forward propagation.&lt;/li&gt;
&lt;li&gt;Compute loss.&lt;/li&gt;
&lt;li&gt;Implement backward propagation to get the gradients.&lt;/li&gt;
&lt;li&gt;Update parameters.&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;div id=&#34;get-layer-sizes&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Get layer sizes&lt;/h3&gt;
&lt;p&gt;A neural network optimizes certain parameters to get to the right output. These parameters are initialized randomly. However, the size of these matrices is dependent upon the number of layers in different layers of neural-net.&lt;/p&gt;
&lt;p&gt;To generate matrices with random parameters, we need to first obtain the size (number of neurons) of all the layers in our neural-net. We’ll write a function to do that. Let’s denote &lt;code&gt;n_x&lt;/code&gt;, &lt;code&gt;n_h&lt;/code&gt;, and &lt;code&gt;n_y&lt;/code&gt; as the number of neurons in input layer, hidden layer, and output layer respectively.&lt;/p&gt;
&lt;p&gt;We will obtain these shapes from our input and output data matrices created above.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;dim(X)[1]&lt;/code&gt; gives us &lt;span class=&#34;math inline&#34;&gt;\(2\)&lt;/span&gt; because the shape of &lt;code&gt;X&lt;/code&gt; is &lt;code&gt;(2, 320)&lt;/code&gt;. We do the same for &lt;code&gt;dim(y)[1]&lt;/code&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;getLayerSize &amp;lt;- function(X, y, hidden_neurons, train=TRUE) {
  n_x &amp;lt;- dim(X)[1]
  n_h &amp;lt;- hidden_neurons
  n_y &amp;lt;- dim(y)[1]   
  
  size &amp;lt;- list(&amp;quot;n_x&amp;quot; = n_x,
               &amp;quot;n_h&amp;quot; = n_h,
               &amp;quot;n_y&amp;quot; = n_y)
  
  return(size)
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As we can see below, the number of neurons is decided based on shape of the input and output matrices.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;layer_size &amp;lt;- getLayerSize(X_train, y_train, hidden_neurons = 4)
layer_size&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## $n_x
## [1] 2
## 
## $n_h
## [1] 4
## 
## $n_y
## [1] 1&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;initialise-parameters&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Initialise parameters&lt;/h3&gt;
&lt;p&gt;Before we start training our parameters, we need to initialize them. Let’s initialize the parameters based on random uniform distribution.&lt;/p&gt;
&lt;p&gt;The function &lt;code&gt;initializeParameters()&lt;/code&gt; takes as argument an input matrix and a list which contains the layer sizes i.e. number of neurons. The function returns the trainable parameters &lt;code&gt;W1, b1, W2, b2&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Our neural-net has 3 layers, which gives us 2 sets of parameter. The first set is &lt;code&gt;W1&lt;/code&gt; and &lt;code&gt;b1&lt;/code&gt;. The second set is &lt;code&gt;W2&lt;/code&gt; and &lt;code&gt;b2&lt;/code&gt;. Note that these parameters exist as matrices.&lt;/p&gt;
&lt;p&gt;These random weights matrices &lt;code&gt;W1, b1, W2, b2&lt;/code&gt; are created based on the layer sizes of the different layers (&lt;code&gt;n_x&lt;/code&gt;, &lt;code&gt;n_h&lt;/code&gt;, and &lt;code&gt;n_y&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;The sizes of these weights matrices are -&lt;/p&gt;
&lt;p&gt;&lt;code&gt;W1&lt;/code&gt; = &lt;code&gt;(n_h, n_x)&lt;/code&gt;&lt;br /&gt;
&lt;code&gt;b1&lt;/code&gt; = &lt;code&gt;(n_h, 1)&lt;/code&gt;&lt;br /&gt;
&lt;code&gt;W2&lt;/code&gt; = &lt;code&gt;(n_y, n_h)&lt;/code&gt;&lt;br /&gt;
&lt;code&gt;b2&lt;/code&gt; = &lt;code&gt;(n_y, 1)&lt;/code&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;initializeParameters &amp;lt;- function(X, list_layer_size){

    m &amp;lt;- dim(data.matrix(X))[2]
    
    n_x &amp;lt;- list_layer_size$n_x
    n_h &amp;lt;- list_layer_size$n_h
    n_y &amp;lt;- list_layer_size$n_y
        
    W1 &amp;lt;- matrix(runif(n_h * n_x), nrow = n_h, ncol = n_x, byrow = TRUE) * 0.01
    b1 &amp;lt;- matrix(rep(0, n_h), nrow = n_h)
    W2 &amp;lt;- matrix(runif(n_y * n_h), nrow = n_y, ncol = n_h, byrow = TRUE) * 0.01
    b2 &amp;lt;- matrix(rep(0, n_y), nrow = n_y)
    
    params &amp;lt;- list(&amp;quot;W1&amp;quot; = W1,
                   &amp;quot;b1&amp;quot; = b1, 
                   &amp;quot;W2&amp;quot; = W2,
                   &amp;quot;b2&amp;quot; = b2)
    
    return (params)
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For our network, the size of our weight matrices are as follows. Remember that, number of input neurons &lt;code&gt;n_x = 2&lt;/code&gt;, hidden neurons &lt;code&gt;n_h = 4&lt;/code&gt;, and output neuron &lt;code&gt;n_y = 1&lt;/code&gt;. &lt;code&gt;layer_size&lt;/code&gt; is calculate above.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;init_params &amp;lt;- initializeParameters(X_train, layer_size)
lapply(init_params, function(x) dim(x))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## $W1
## [1] 4 2
## 
## $b1
## [1] 4 1
## 
## $W2
## [1] 1 4
## 
## $b2
## [1] 1 1&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;define-the-activation-functions.&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Define the Activation Functions.&lt;/h3&gt;
&lt;p&gt;We implement the &lt;code&gt;sigmoid()&lt;/code&gt; activation function for the output layer.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;sigmoid &amp;lt;- function(x){
    return(1 / (1 + exp(-x)))
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[S(x) =  \frac {1} {1 + e^{-x}}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;tanh()&lt;/code&gt; function is already present in R.&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[T(x) =  \frac {e^x - e^{-x}} {e^x + e^{-x}}\]&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Here, we plot both activation functions side-by-side for comparison.
&lt;img src=&#34;/post/2020-07-11-shallow-neural-net-from-scratch-using-r-part-1/index_files/figure-html/unnamed-chunk-23-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;forward-propagation&#34; class=&#34;section level3&#34;&gt;
&lt;h3&gt;Forward Propagation&lt;/h3&gt;
&lt;p&gt;Now, onto defining the forward propagation. The function &lt;code&gt;forwardPropagation()&lt;/code&gt; takes as arguments the input matrix &lt;code&gt;X&lt;/code&gt;, the parameters list &lt;code&gt;params&lt;/code&gt;, and the list of &lt;code&gt;layer_sizes&lt;/code&gt;. We extract the layers sizes and weights from the respective functions defined above. To perform matrix multiplication, we use the &lt;code&gt;%*%&lt;/code&gt; operator.&lt;/p&gt;
&lt;p&gt;Before we perform the matrix multiplications, we need to reshape the parameters &lt;code&gt;b1&lt;/code&gt; and &lt;code&gt;b2&lt;/code&gt;. Why do we do this? Let’s find out. Note that, the parameter shapes are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;W1&lt;/code&gt;: &lt;code&gt;(4, 2)&lt;/code&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;b1&lt;/code&gt;: &lt;code&gt;(4, 1)&lt;/code&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;W2&lt;/code&gt;: &lt;code&gt;(1, 4)&lt;/code&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;b2&lt;/code&gt; : &lt;code&gt;(1, 1)&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;And the layers sizes are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;n_x&lt;/code&gt; = &lt;code&gt;2&lt;/code&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;n_h&lt;/code&gt; = &lt;code&gt;4&lt;/code&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;n_y&lt;/code&gt; = &lt;code&gt;1&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Finally, shape of input matrix &lt;span class=&#34;math inline&#34;&gt;\(X\)&lt;/span&gt; (input layer):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;X&lt;/code&gt;: &lt;code&gt;(2, 320)&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If we talk about the &lt;strong&gt;input =&amp;gt; hidden&lt;/strong&gt;; the hidden layer obtained by the equation &lt;code&gt;A1 = activation(y1) = W1 %*% X + b1&lt;/code&gt;, would be as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;For the matrix multiplication of &lt;code&gt;W1&lt;/code&gt; and &lt;code&gt;X&lt;/code&gt;, their shapes are correct by default: &lt;code&gt;(4, 2) x (2, 320)&lt;/code&gt;. The shape of the output matrix &lt;code&gt;W1 %*% X&lt;/code&gt; is &lt;code&gt;(4, 320)&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Now, &lt;code&gt;b1&lt;/code&gt; is of shape &lt;code&gt;(4, 1)&lt;/code&gt;. Since, &lt;code&gt;W1 %*% X&lt;/code&gt; is of the shape &lt;code&gt;(4, 320)&lt;/code&gt;, we need to repeat it &lt;code&gt;b1&lt;/code&gt; 320 times, one for each input sample We do that using the command &lt;code&gt;rep(b1, m)&lt;/code&gt; where &lt;code&gt;m&lt;/code&gt; is calculated as &lt;code&gt;dim(X)[2]&lt;/code&gt; which selects the second dimension of the shape of &lt;code&gt;X&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The shape of &lt;code&gt;A1&lt;/code&gt; is &lt;code&gt;(4, 320)&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In the case of &lt;strong&gt;hidden =&amp;gt; output&lt;/strong&gt;; the output obtained by the equation &lt;code&gt;y2 = W2 %*% A1 + b2&lt;/code&gt;, would be as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;To shapes of &lt;code&gt;W2&lt;/code&gt; and &lt;code&gt;A1&lt;/code&gt; are correct for us to perform matrix multiplication on them. &lt;code&gt;W2&lt;/code&gt; is &lt;code&gt;(1, 4)&lt;/code&gt; and &lt;code&gt;A1&lt;/code&gt; is &lt;code&gt;(4, 320)&lt;/code&gt;. The output &lt;code&gt;W2 %*% A1&lt;/code&gt; has the shape &lt;code&gt;(1, 320)&lt;/code&gt;. &lt;code&gt;b2&lt;/code&gt; has a shape of &lt;code&gt;(1, 1)&lt;/code&gt;. We will again repeat &lt;code&gt;b2&lt;/code&gt; like we did above. So, &lt;code&gt;b2&lt;/code&gt; now becomes &lt;code&gt;(1, 320)&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The shape of &lt;code&gt;A2&lt;/code&gt; is now &lt;code&gt;(1, 320)&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We use the &lt;code&gt;tanh()&lt;/code&gt; activation for the hidden layer and &lt;code&gt;sigmoid()&lt;/code&gt; activation for the output layer.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;forwardPropagation &amp;lt;- function(X, params, list_layer_size){
    
    m &amp;lt;- dim(X)[2]
    n_h &amp;lt;- list_layer_size$n_h
    n_y &amp;lt;- list_layer_size$n_y
    
    W1 &amp;lt;- params$W1
    b1 &amp;lt;- params$b1
    W2 &amp;lt;- params$W2
    b2 &amp;lt;- params$b2
    
    b1_new &amp;lt;- matrix(rep(b1, m), nrow = n_h)
    b2_new &amp;lt;- matrix(rep(b2, m), nrow = n_y)
    
    Z1 &amp;lt;- W1 %*% X + b1_new
    A1 &amp;lt;- sigmoid(Z1)
    Z2 &amp;lt;- W2 %*% A1 + b2_new
    A2 &amp;lt;- sigmoid(Z2)
    
    cache &amp;lt;- list(&amp;quot;Z1&amp;quot; = Z1,
                  &amp;quot;A1&amp;quot; = A1, 
                  &amp;quot;Z2&amp;quot; = Z2,
                  &amp;quot;A2&amp;quot; = A2)

    return (cache)
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Even though we only need the value &lt;code&gt;A2&lt;/code&gt; for forward propagation, you’ll notice we return all other calculated values as well. We do this because these values will be needed during backpropagation. Saving them here will reduce the the time it takes for backpropagation because we don’t have to calculate it again.&lt;/p&gt;
&lt;p&gt;Another thing to notice is the &lt;code&gt;Z&lt;/code&gt; and &lt;code&gt;A&lt;/code&gt; of a particular layer will always have the same shape. This is because &lt;code&gt;A = activation(Z)&lt;/code&gt; which does not change the shape of &lt;code&gt;Z&lt;/code&gt;. An activation function only introduces non-linearity in a network.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;fwd_prop &amp;lt;- forwardPropagation(X_train, init_params, layer_size)
lapply(fwd_prop, function(x) dim(x))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## $Z1
## [1]   4 320
## 
## $A1
## [1]   4 320
## 
## $Z2
## [1]   1 320
## 
## $A2
## [1]   1 320&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&#34;end-of-part-1&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;End of Part 1&lt;/h2&gt;
&lt;p&gt;We have reached the end of Part1 here. In the next and final part, we will implement backpropagation and evaluate our model. Stay tuned!&lt;/p&gt;
&lt;/div&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2020/07/20/shallow-neural-net-from-scratch-using-r-part-1/&#39;;&lt;/script&gt;
      </description>
    </item>
    
  </channel>
</rss>
