<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/how-to-build-your-own-neural-network-from-scratch-in-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.tychobra.com/posts/2018_10_09_nn_from_scratch/"> Posts on Tychobra</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Last week I ran across <a rel="nofollow" href="https://towardsdatascience.com/how-to-build-your-own-neural-network-from-scratch-in-python-68998a08e4f6" target="_blank">this great post on creating a neural network in Python</a>. It walks through the very basics of neural networks and creates a working example using Python. I enjoyed the simple hands on approach the author used, and I was interested to see how we might make the same model using R.</p>
<p>In this post we recreate the above-mentioned Python neural network from scratch in R. Our R refactor is focused on simplicity and understandability; we are not concerned with writing the most efficient or elegant code.</p>
<p>Our very basic neural network will have 2 layers. Below is a diagram of the network:</p>
<p><img src="https://i1.wp.com/res.cloudinary.com/dxqnb8xjb/image/upload/v1539018324/nn_diagram_d7gs7e.png?w=456&ssl=1" data-recalc-dims="1"></p>
<p>For background information, please read over the Python post. It may be helpful to open the Python post and compare the chunks of Python code to the corresponding R code below. The full Python code to train the model is not available in the body of the Python post, but fortunately it is included in the comments; so, scroll down on the Python post if you are looking for it.</p>
<p>Let’s get started with R!</p>
<div>
<h3>Create Training Data</h3>
<p>First, we create the data to train the neural network.</p>
<pre><code># predictor variables
X &lt;- matrix(c(
  0,0,1,
  0,1,1,
  1,0,1,
  1,1,1
),
  ncol = 3,
  byrow = TRUE
)

# observed outcomes
y &lt;- c(0, 1, 1, 0)

# print the data so we can take a quick look at it
cbind(X, y)</code></pre>
<pre><code>##            y
## [1,] 0 0 1 0
## [2,] 0 1 1 1
## [3,] 1 0 1 1
## [4,] 1 1 1 0</code></pre>
<p>The above data contains 4 observations; each row is an observation. The 3 columns on the left (i.e. the <code>X</code> object) are used with the observed outcomes (“y” column on the right) to train the model. Once our model is trained, we will be able to pass new predictor variables (i.e. new rows of <code>X</code>) to the model and predict y values that have not yet been observed.</p>
</div>
<div>
<h3>Create an object to store the state of our neural network</h3>
<p>Now that we have our data, we need to create the model. First, we create an object to store the state of the model.</p>
<pre><code># generate a random value between 0 and 1 for each
# element in X.  This will be used as our initial weights
# for layer 1
rand_vector &lt;- runif(ncol(X) * nrow(X))

# convert above vector into a matrix
rand_matrix &lt;- matrix(
  rand_vector,
  nrow = ncol(X),
  ncol = nrow(X),
  byrow = TRUE
)

# this list stores the state of our neural net as it is trained
my_nn &lt;- list(
  # predictor variables
  input = X,
  # weights for layer 1
  weights1 = rand_matrix,
  # weights for layer 2
  weights2 = matrix(runif(4), ncol = 1),
  # actual observed
  y = y,
  # stores the predicted outcome
  output = matrix(
    rep(0, times = 4),
    ncol = 1
  )
)</code></pre>
</div>
<div>
<h3>Activation Function</h3>
<p>Now that we have some data to work with (<code>X</code> and <code>y</code>) and a list to store the state of our model (<code>my_nn</code>), we can put together the functions to train our model.</p>
<p>Here we define the activation function. The activation function converts a layer’s inputs to outputs. The outputs are then passed to the next layer. The <em>Sigmoid</em> activation function is used in our model.</p>
<pre><code>#' the activation function
sigmoid &lt;- function(x) {
  1.0 / (1.0 + exp(-x))
}

#' the derivative of the activation function
sigmoid_derivative &lt;- function(x) {
  x * (1.0 - x)
}</code></pre>
</div>
<div>
<h3>Loss Function</h3>
<p>The loss function is used to determine the goodness of fit of the model. We use the <em>Sum-of-Squares Error</em> as our loss function.</p>
<pre><code>loss_function &lt;- function(nn) {
  sum((nn$y - nn$output) ^ 2)
}</code></pre>
<p>The goal of the neural network is to find weights for each layer that minimize the result of the loss function.</p>
</div>
<div>
<h3>Feedforward and Back Propagation</h3>
<p>In order to minimize the loss function we perform feedforward and backpropagation. Feedforward applies the activation function to the layers and produces a predicted outcome.</p>
<pre><code>feedforward &lt;- function(nn) {

  nn$layer1 &lt;- sigmoid(nn$input %*% nn$weights1)
  nn$output &lt;- sigmoid(nn$layer1 %*% nn$weights2)

  nn
}</code></pre>
<p>Backpropagation takes the predicted outcome, resulting from the feedforward step, and adjust the layer weights to reduce the loss function.</p>
<pre><code>backprop &lt;- function(nn) {

  # application of the chain rule to find derivative of the loss function with 
  # respect to weights2 and weights1
  d_weights2 &lt;- (
    t(nn$layer1) %*%
    # `2 * (nn$y - nn$output)` is the derivative of the sigmoid loss function
    (2 * (nn$y - nn$output) *
    sigmoid_derivative(nn$output))
  )

  d_weights1 &lt;- ( 2 * (nn$y - nn$output) * sigmoid_derivative(nn$output)) %*% 
    t(nn$weights2)
  d_weights1 &lt;- d_weights1 * sigmoid_derivative(nn$layer1)
  d_weights1 &lt;- t(nn$input) %*% d_weights1
  
  # update the weights using the derivative (slope) of the loss function
  nn$weights1 &lt;- nn$weights1 + d_weights1
  nn$weights2 &lt;- nn$weights2 + d_weights2

  nn
}</code></pre>
</div>
<div>
<h3>Train the Model</h3>
<p>We are now ready to train our model. The training process repeatedly calls <code>feedforward()</code> and <code>backprop()</code> in order to reduce the loss function.</p>
<pre><code># number of times to perform feedforward and backpropagation
n &lt;- 1500

# data frame to store the results of the loss function.
# this data frame is used to produce the plot in the 
# next code chunk
loss_df &lt;- data.frame(
  iteration = 1:n,
  loss = vector(&quot;numeric&quot;, length = n)
)

for (i in seq_len(1500)) {
  my_nn &lt;- feedforward(my_nn)
  my_nn &lt;- backprop(my_nn)

  # store the result of the loss function.  We will plot this later
  loss_df$loss[i] &lt;- loss_function(my_nn)
}

# print the predicted outcome next to the actual outcome
data.frame(
  &quot;Predicted&quot; = round(my_nn$output, 3),
  &quot;Actual&quot; = y
)</code></pre>
<pre><code>##   Predicted Actual
## 1     0.017      0
## 2     0.975      1
## 3     0.982      1
## 4     0.024      0</code></pre>
<p>Above you can see that the predicted values are fairly close to the actual observed values.</p>
<p>The plot below displays the result of the loss function as the model is trained. The objective of the model training is to minimize the result of the loss function (Y axis), and we can see that as we progress in iterations (X axis), the result of the loss function approaches zero.</p>
<pre><code># plot the cost
library(ggplot2)

ggplot(data = loss_df, aes(x = iteration, y = loss)) +
  geom_line()</code></pre>
<p><img src="https://i1.wp.com/www.tychobra.com/posts/2018_10_09_nn_from_scratch_files/figure-html/plot-1.png?w=450&ssl=1" data-recalc-dims="1"></p>
</div>
<div>
<h3>Conclusion</h3>
<p>The Python post was a fun and informative way to explore how the most basic steps in neural networks fit together. Converting the Python to R gave me additional insights and understanding into the inner workings of the Python code.</p>
<p>The example neural network is extremely simple, and the data/prediction is not particularly meaningful, but I enjoyed walking through the basic fundamentals of a neural network. I hope you enjoyed it as well. Thanks for reading.</p>
</div>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://www.tychobra.com/posts/2018_10_09_nn_from_scratch/"> Posts on Tychobra</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/-6958KEcHHc" height="1"></a></div>