<h2>A Brief Introduction</h2>
<p>Linear regression is a classic supervised statistical technique for predictive modelling which is based on the linear hypothesis:</p>
<h2><strong><em>y = mx + c</em></strong></h2>
<p>where <em>y </em>is the <strong>response</strong> or outcome variable, <em>m</em> is the <strong>gradient</strong> of the linear trend-line, <em>x</em> is the <strong>predictor</strong> variable and <em>c</em> is the <strong>intercept</strong>. The intercept is the point on the y-axis where the value of the predictor <em>x</em> is zero.</p>
<p>In order to apply the linear hypothesis to a dataset with the end aim of modelling the situation under investigation, there needs to be a linear relationship between the variables in question. A simple scatterplot is an excellent visual tool to assess linearity between two variables. Below is an example of a linear relationship between miles per gallon (mpg) and engine displacement volume (disp) of automobiles which could be modelled using linear regression. Note that there are various methods of transforming non-linear data to make them appear more linear such as log and square root transformations but we won’t discuss those here.</p>
<pre>attach(mtcars)
plot(disp, mpg, col = &quot;blue&quot;, pch = 20)</pre>
<p><img sizes="(max-width: 739px) 100vw, 739px" data-image-description="" data-orig-file="https://i0.wp.com/sw23993.files.wordpress.com/2017/02/rplot.png?w=456&amp;ssl=1" data-orig-size="791,348" data-image-title="rplot" class="wp-image-711" data-comments-opened="1" data-recalc-dims="1" data-attachment-id="711" data-permalink="https://sw23993.wordpress.com/2017/02/12/implementing-the-gradient-descent-algorithm-in-r/rplot-5/" alt="rplot" data-medium-file="https://i0.wp.com/sw23993.files.wordpress.com/2017/02/rplot.png?w=456&amp;ssl=1?w=300" data-large-file="https://i0.wp.com/sw23993.files.wordpress.com/2017/02/rplot.png?w=456&amp;ssl=1?w=739" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" src="https://i0.wp.com/sw23993.files.wordpress.com/2017/02/rplot.png?w=456&ssl=1"></p>
<p>Now, in order to fit a good model, appropriate values for the intercept and slope must be found. R has a nice function, lm(), which creates a linear model from which we can extract the most appropriate intercept and slope (coefficients).</p>
<pre>model &lt;- lm(mpg ~ disp, data = mtcars)
coef(model)

(Intercept)        disp 
29.59985476 -0.04121512</pre>
<p>We see that the intercept is set at 29.59985476 on the y-axis and that the gradient is -0.04121512. The negative gradient tells us that there is an inverse relationship between mpg and displacement with one unit increase in displacement resulting in a 0.04 unit decrease in mpg.</p>
<p>How are these intercept and gradient values calculated one may ask? In finding the appropriate values, the goal is to reduce the value of a statistic known as the <strong>mean squared error (MSE)</strong>:</p>
<h2><strong><em>MSE = Σ(y – y_preds)² / n</em></strong></h2>
<p> </p>
<p>where<em> y</em> represents the observed value of the response variable, <em>y_preds</em> represents the predicted <em>y</em> value from the linear model after plugging in values for the intercept and slope, and <em>n</em> is the number of observations in the dataset. Each set of <em>xy</em> data points are iterated over to find the squared error, all squared errors are summed and the sum is divided by<em> n</em> to get the MSE.</p>
<p>Using the linear model we created earlier, we can obtain <em>y</em> predictions and plot them on the scatterplot as a regression line. We use the predict() function in base R and plot the predicted values using abline().</p>
<pre>y_preds &lt;- predict(model)
abline(model)</pre>
<p><img sizes="(max-width: 739px) 100vw, 739px" data-image-description="" data-orig-file="https://i0.wp.com/sw23993.files.wordpress.com/2017/02/rplot01.png?w=456&amp;ssl=1" data-orig-size="791,348" data-image-title="rplot01" data-comments-opened="1" class="wp-image-769" data-recalc-dims="1" data-attachment-id="769" data-permalink="https://sw23993.wordpress.com/2017/02/12/implementing-the-gradient-descent-algorithm-in-r/rplot01-4/" alt="rplot01" data-medium-file="https://i0.wp.com/sw23993.files.wordpress.com/2017/02/rplot01.png?w=456&amp;ssl=1?w=300" data-large-file="https://i0.wp.com/sw23993.files.wordpress.com/2017/02/rplot01.png?w=456&amp;ssl=1?w=739" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" src="https://i0.wp.com/sw23993.files.wordpress.com/2017/02/rplot01.png?w=456&ssl=1"></p>
<p>Next, we can calculate the MSE by summing the squared differences between observed <em>y</em> values and our predicted <em>y</em> values then dividing by the number of observations<em> n.</em> This gives a MSE of 9.911209 for this linear model.</p>
<pre>errors &lt;- unname((mpg - y_preds) ^ 2)
sum(errors) / length(mpg)</pre>
<p> </p>
<h2>The Gradient Descent Algorithm</h2>
<p>I now want to introduce the Gradient Descent Algorithm which can be used to find the optimal intercept and gradient for any set of data in which a linear relationship exists. There are various ways of calculating the intercept and gradient values but I was recently playing around with this algorithm in Python and wanted to try it out in R.</p>
<p>The goal of the algorithm is to find the intercept and gradient values which correspond to the lowest possible MSE. It achieves this through iteration over each set of <em>xy</em> data pairs whereby new intercept and gradient values are calculated as well as a new MSE. Then, the new MSE is subtracted from the old MSE and, if the difference is negligible, the optimal values are found.</p>
<p>The function I created below is how I implemented the gradient descent algorithm and applied it to the data we are looking at here. We pass the function our <em>x</em> and <em>y</em> variables. We also pass it the  <em>l</em>earning rate which is the magnitude of the steps the algorithm takes along the slope of the MSE function. This can take different values but for this example it is set to 0.0000293. The convergence threshold is set to 0.001. This is the difference between the old MSE and new MSE on each iteration. Finally, we pass the value for <em>n</em> and set the maximum number of iterations we wish to carry out before the loop terminates.</p>
<pre>gradientDesc &lt;- function(x, y, learn_rate, conv_threshold, n, max_iter) {
  plot(x, y, col = &quot;blue&quot;, pch = 20)
  m &lt;- runif(1, 0, 1)
  c &lt;- runif(1, 0, 1)
  yhat &lt;- m * x + c
  MSE &lt;- sum((y - yhat) ^ 2) / n
  converged = F
  iterations = 0
  while(converged == F) {
    ## Implement the gradient descent algorithm
    m_new &lt;- m - learn_rate * ((1 / n) * (sum((yhat - y) * x)))
    c_new &lt;- c - learn_rate * ((1 / n) * (sum(yhat - y)))
    m &lt;- m_new
    c &lt;- c_new
    yhat &lt;- m * x + c
    MSE_new &lt;- sum((y - yhat) ^ 2) / n
    if(MSE - MSE_new &lt;= conv_threshold) {
      abline(c, m) 
      converged = T
      return(paste(&quot;Optimal intercept:&quot;, c, &quot;Optimal slope:&quot;, m))
    }
    iterations = iterations + 1
    if(iterations > max_iter) { 
      abline(c, m) 
      converged = T
      return(paste(&quot;Optimal intercept:&quot;, c, &quot;Optimal slope:&quot;, m))
    }
  }
}


# Run the function 

gradientDesc(disp, mpg, 0.0000293, 0.001, 32, 2500000)</pre>
<p> </p>
<p>The graphical output and values for the intercept and gradient returned by the function are given below:</p>
<p><img sizes="(max-width: 739px) 100vw, 739px" data-image-description="" data-orig-file="https://i1.wp.com/sw23993.files.wordpress.com/2017/02/rplot02.png?w=456&amp;ssl=1" data-orig-size="791,348" data-image-title="rplot02" data-comments-opened="1" class="wp-image-810" data-recalc-dims="1" data-attachment-id="810" data-permalink="https://sw23993.wordpress.com/2017/02/12/implementing-the-gradient-descent-algorithm-in-r/rplot02-5/" alt="rplot02" data-medium-file="https://i1.wp.com/sw23993.files.wordpress.com/2017/02/rplot02.png?w=456&amp;ssl=1?w=300" data-large-file="https://i1.wp.com/sw23993.files.wordpress.com/2017/02/rplot02.png?w=456&amp;ssl=1?w=739" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" src="https://i1.wp.com/sw23993.files.wordpress.com/2017/02/rplot02.png?w=456&ssl=1"></p>
<pre>[1] &quot;Optimal intercept: 29.5998514475591 Optimal slope: -0.0412151087554405&quot;</pre>
<p> </p>
<p>The matches are good. Remember our calculated values for the intercept and gradient from earlier? Here they are again for comparison:</p>
<pre>coef(model)

(Intercept)        disp 
29.59985476 -0.04121512</pre>
<p> </p>
<p> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sw23993.wordpress.com/692/"><img alt="" src="http://feeds.wordpress.com/1.0/comments/sw23993.wordpress.com/692/" border="0"></a> <img alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" border="0" data-recalc-dims="1"></p>
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/guy-Z9cBVj0">