-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathLoess-Regression-With-R.html
307 lines (271 loc) · 17 KB
/
Loess-Regression-With-R.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
<!DOCTYPE html>
<html>
<head>
<title>Loess Regression and Smoothing With R</title>
<meta charset="utf-8">
<meta name="Description" content="R Language Tutorials for Advanced Statistics">
<meta name="Keywords" content="R, Tutorial, Machine learning, Statistics, Data Mining, Analytics, Data science, Linear Regression, Logistic Regression, Time series, Forecasting">
<meta name="Distribution" content="Global">
<meta name="Author" content="Selva Prabhakaran">
<meta name="Robots" content="index, follow">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="/screenshots/iconb-64.png" type="image/x-icon" />
<link href="www/bootstrap.min.css" rel="stylesheet">
<link href="www/highlight.css" rel="stylesheet">
<link href='http://fonts.googleapis.com/css?family=Inconsolata:400,700'
rel='stylesheet' type='text/css'>
<!-- Color Script -->
<style type="text/css">
a {
color: #3675C5;
color: rgb(25, 145, 248);
color: #4582ec;
color: #3F73D8;
}
li {
line-height: 1.65;
}
/* reduce spacing around math formula*/
.MathJax_Display {
margin: 0em 0em;
}
</style>
<!-- Add Google search -->
<script language="Javascript" type="text/javascript">
function my_search_google()
{
var query = document.getElementById("my-google-search").value;
window.open("http://google.com/search?q=" + query
+ "%20site:" + "http://r-statistics.co");
}
</script>
</head>
<body>
<div class="container">
<div class="masthead">
<!--
<ul class="nav nav-pills pull-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Table of contents<b class="caret"></b>
</a>
<ul class="dropdown-menu pull-right" role="menu">
<li class="dropdown-header"></li>
<li class="dropdown-header">Tutorial</li>
<li><a href="R-Tutorial.html">R Tutorial</a></li>
<li class="dropdown-header">ggplot2</li>
<li><a href="ggplot2-Tutorial-With-R.html">ggplot2 Short Tutorial</a></li>
<li><a href="Complete-Ggplot2-Tutorial-Part1-With-R-Code.html">ggplot2 Tutorial 1 - Intro</a></li>
<li><a href="Complete-Ggplot2-Tutorial-Part2-Customizing-Theme-With-R-Code.html">ggplot2 Tutorial 2 - Theme</a></li>
<li><a href="Top50-Ggplot2-Visualizations-MasterList-R-Code.html">ggplot2 Tutorial 3 - Masterlist</a></li>
<li><a href="ggplot2-cheatsheet.html">ggplot2 Quickref</a></li>
<li class="dropdown-header">Foundations</li>
<li><a href="Linear-Regression.html">Linear Regression</a></li>
<li><a href="Statistical-Tests-in-R.html">Statistical Tests</a></li>
<li><a href="Missing-Value-Treatment-With-R.html">Missing Value Treatment</a></li>
<li><a href="Outlier-Treatment-With-R.html">Outlier Analysis</a></li>
<li><a href="Variable-Selection-and-Importance-With-R.html">Feature Selection</a></li>
<li><a href="Model-Selection-in-R.html">Model Selection</a></li>
<li><a href="Logistic-Regression-With-R.html">Logistic Regression</a></li>
<li><a href="Environments.html">Advanced Linear Regression</a></li>
<li class="dropdown-header">Advanced Regression Models</li>
<li><a href="adv-regression-models.html">Advanced Regression Models</a></li>
<li class="dropdown-header">Time Series</li>
<li><a href="Time-Series-Analysis-With-R.html">Time Series Analysis</a></li>
<li><a href="Time-Series-Forecasting-With-R.html">Time Series Forecasting </a></li>
<li><a href="Time-Series-Forecasting-With-R-part2.html">More Time Series Forecasting</a></li>
<li class="dropdown-header">High Performance Computing</li>
<li><a href="Parallel-Computing-With-R.html">Parallel computing</a></li>
<li><a href="Strategies-To-Improve-And-Speedup-R-Code.html">Strategies to Speedup R code</a></li>
<li class="dropdown-header">Useful Techniques</li>
<li><a href="Association-Mining-With-R.html">Association Mining</a></li>
<li><a href="Multi-Dimensional-Scaling-With-R.html">Multi Dimensional Scaling</a></li>
<li><a href="Profiling.html">Optimization</a></li>
<li><a href="Information-Value-With-R.html">InformationValue package</a></li>
</ul>
</li>
</ul>
-->
<ul class="nav nav-pills pull-right">
<div class="input-group">
<form onsubmit="my_search_google()">
<input type="text" class="form-control" id="my-google-search" placeholder="Search..">
<form>
</div><!-- /input-group -->
</ul><!-- /.col-lg-6 -->
<h3 class="muted"><a href="/">r-statistics.co</a><small> by Selva Prabhakaran</small></h3>
<hr>
</div>
<div class="row">
<div class="col-xs-12 col-sm-3" id="nav">
<div class="well">
<li>
<ul class="list-unstyled">
<li class="dropdown-header"></li>
<li class="dropdown-header">Tutorial</li>
<li><a href="R-Tutorial.html">R Tutorial</a></li>
<li class="dropdown-header">ggplot2</li>
<li><a href="ggplot2-Tutorial-With-R.html">ggplot2 Short Tutorial</a></li>
<li><a href="Complete-Ggplot2-Tutorial-Part1-With-R-Code.html">ggplot2 Tutorial 1 - Intro</a></li>
<li><a href="Complete-Ggplot2-Tutorial-Part2-Customizing-Theme-With-R-Code.html">ggplot2 Tutorial 2 - Theme</a></li>
<li><a href="Top50-Ggplot2-Visualizations-MasterList-R-Code.html">ggplot2 Tutorial 3 - Masterlist</a></li>
<li><a href="ggplot2-cheatsheet.html">ggplot2 Quickref</a></li>
<li class="dropdown-header">Foundations</li>
<li><a href="Linear-Regression.html">Linear Regression</a></li>
<li><a href="Statistical-Tests-in-R.html">Statistical Tests</a></li>
<li><a href="Missing-Value-Treatment-With-R.html">Missing Value Treatment</a></li>
<li><a href="Outlier-Treatment-With-R.html">Outlier Analysis</a></li>
<li><a href="Variable-Selection-and-Importance-With-R.html">Feature Selection</a></li>
<li><a href="Model-Selection-in-R.html">Model Selection</a></li>
<li><a href="Logistic-Regression-With-R.html">Logistic Regression</a></li>
<li><a href="Environments.html">Advanced Linear Regression</a></li>
<li class="dropdown-header">Advanced Regression Models</li>
<li><a href="adv-regression-models.html">Advanced Regression Models</a></li>
<li class="dropdown-header">Time Series</li>
<li><a href="Time-Series-Analysis-With-R.html">Time Series Analysis</a></li>
<li><a href="Time-Series-Forecasting-With-R.html">Time Series Forecasting </a></li>
<li><a href="Time-Series-Forecasting-With-R-part2.html">More Time Series Forecasting</a></li>
<li class="dropdown-header">High Performance Computing</li>
<li><a href="Parallel-Computing-With-R.html">Parallel computing</a></li>
<li><a href="Strategies-To-Improve-And-Speedup-R-Code.html">Strategies to Speedup R code</a></li>
<li class="dropdown-header">Useful Techniques</li>
<li><a href="Association-Mining-With-R.html">Association Mining</a></li>
<li><a href="Multi-Dimensional-Scaling-With-R.html">Multi Dimensional Scaling</a></li>
<li><a href="Profiling.html">Optimization</a></li>
<li><a href="Information-Value-With-R.html">InformationValue package</a></li>
</ul>
</li>
</div>
<div class="well">
<p>Stay up-to-date. <a href="https://docs.google.com/forms/d/1xkMYkLNFU9U39Dd8S_2JC0p8B5t6_Yq6zUQjanQQJpY/viewform">Subscribe!</a></p>
<p><a href="https://docs.google.com/forms/d/13GrkCFcNa-TOIllQghsz2SIEbc-YqY9eJX02B19l5Ow/viewform">Chat!</a></p>
</div>
<h4>Contents</h4>
<ul class="list-unstyled" id="toc"></ul>
<!--
<hr>
<p><a href="/contribute.html">How to contribute</a></p>
<p><a class="btn btn-primary" href="">Edit this page</a></p>
-->
</div>
<div id="content" class="col-xs-12 col-sm-8 pull-right">
<blockquote>
<p>Loess Regression is the most common method used to smoothen a volatile time series. It is a non-parametric methods where least squares regression is performed in localized subsets, which makes it a suitable candidate for smoothing any numerical vector.</p>
</blockquote>
<h2>Introduction</h2>
<p><em>Loess</em> short for Local Regression is a non-parametric approach that fits multiple regressions in local neighborhood. This can be particularly resourceful, if you know that your <span class="math inline"><em>X</em></span> variables are bound within a range.</p>
<p>Loess regression can be applied using the <code>loess()</code> on a numerical vector to smoothen it and to predict the Y locally (i.e, within the trained values of <span class="math inline"><em>X</em><em>s</em></span>). The size of the neighborhood can be controlled using the <code>span</code> argument, which ranges between 0 to 1. It controls the degree of smoothing. So, the greater the value of <code>span</code>, more smooth is the fitted curve.</p>
<p>The predictor variable can just be indices from 1 to number of observations in the absence of explanatory variables. If other explanatory variables are available, they can be used as well (maximum of 4).</p>
<h2>Example</h2>
<p>For this example we will try to locally regress and smooth the <em>median duration of unemployment</em> based on the <code>economics</code> dataset from <code>ggplot2</code> package. We consider only the first 80 rows for this analysis, so it is easier to observe the degree of smoothing in the graphs below.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">data</span>(economics, <span class="dt">package=</span><span class="st">"ggplot2"</span>) <span class="co"># load data</span>
economics$index <-<span class="st"> </span><span class="dv">1</span>:<span class="kw">nrow</span>(economics) <span class="co"># create index variable</span>
economics <-<span class="st"> </span>economics[<span class="dv">1</span>:<span class="dv">80</span>, ] <span class="co"># retail 80rows for better graphical understanding</span>
loessMod10 <-<span class="st"> </span><span class="kw">loess</span>(uempmed ~<span class="st"> </span>index, <span class="dt">data=</span>economics, <span class="dt">span=</span><span class="fl">0.10</span>) <span class="co"># 10% smoothing span</span>
loessMod25 <-<span class="st"> </span><span class="kw">loess</span>(uempmed ~<span class="st"> </span>index, <span class="dt">data=</span>economics, <span class="dt">span=</span><span class="fl">0.25</span>) <span class="co"># 25% smoothing span</span>
loessMod50 <-<span class="st"> </span><span class="kw">loess</span>(uempmed ~<span class="st"> </span>index, <span class="dt">data=</span>economics, <span class="dt">span=</span><span class="fl">0.50</span>) <span class="co"># 50% smoothing span</span></code></pre></div>
<h2>Predict Loess</h2>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># get smoothed output</span>
smoothed10 <-<span class="st"> </span><span class="kw">predict</span>(loessMod10)
smoothed25 <-<span class="st"> </span><span class="kw">predict</span>(loessMod25)
smoothed50 <-<span class="st"> </span><span class="kw">predict</span>(loessMod50) </code></pre></div>
<p><img src='screenshots/Loess-Smoothing.png' width='528' height='393' /></p>
<p>From above plot, you would notice that as the span increases, the smoothing of the curve also increases.</p>
<h5>Code for Plot</h5>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Plot it</span>
<span class="kw">plot</span>(economics$uempmed, <span class="dt">x=</span>economics$date, <span class="dt">type=</span><span class="st">"l"</span>, <span class="dt">main=</span><span class="st">"Loess Smoothing and Prediction"</span>, <span class="dt">xlab=</span><span class="st">"Date"</span>, <span class="dt">ylab=</span><span class="st">"Unemployment (Median)"</span>)
<span class="kw">lines</span>(smoothed10, <span class="dt">x=</span>economics$date, <span class="dt">col=</span><span class="st">"red"</span>)
<span class="kw">lines</span>(smoothed25, <span class="dt">x=</span>economics$date, <span class="dt">col=</span><span class="st">"green"</span>)
<span class="kw">lines</span>(smoothed50, <span class="dt">x=</span>economics$date, <span class="dt">col=</span><span class="st">"blue"</span>)</code></pre></div>
<h2>Finding the optimal smoothing span</h2>
<p>As the smoothing <code>span</code> changes, the accuracy of the fitted curve also changes. If your intent is to minimize the error, the <code>optim()</code> can be used to find that value of <code>span</code>, that minimizes the <em>Sum of Squared Errors (SSE)</em>. For this case, it is graphically intuitive that lower SSE will likely be achieved at lower values of <code>span</code>, but for more challenging cases, <code>optimizing</code> span could help.</p>
<p>To implement <code>optim()</code>, we define the function that computes the <em>SSE</em>. An error handling mechanism is needed to address very low values of <code>span</code> and cases where the non-numerics are produced. The simulated annealing method (<code>SANN</code>) is implemented here to find the <code>span</code> that gives minimal <em>SSE</em>. The <code>par</code> argument specifies the first value of the <code>span</code> at which <code>optim()</code> will begin the search.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># define function that returns the SSE</span>
calcSSE <-<span class="st"> </span>function(x){
loessMod <-<span class="st"> </span><span class="kw">try</span>(<span class="kw">loess</span>(uempmed ~<span class="st"> </span>index, <span class="dt">data=</span>economics, <span class="dt">span=</span>x), <span class="dt">silent=</span>T)
res <-<span class="st"> </span><span class="kw">try</span>(loessMod$residuals, <span class="dt">silent=</span>T)
if(<span class="kw">class</span>(res)!=<span class="st">"try-error"</span>){
if((<span class="kw">sum</span>(res, <span class="dt">na.rm=</span>T) ><span class="st"> </span><span class="dv">0</span>)){
sse <-<span class="st"> </span><span class="kw">sum</span>(res^<span class="dv">2</span>)
}
}else{
sse <-<span class="st"> </span><span class="dv">99999</span>
}
<span class="kw">return</span>(sse)
}
<span class="co"># Run optim to find span that gives min SSE, starting at 0.5</span>
<span class="kw">optim</span>(<span class="dt">par=</span><span class="kw">c</span>(<span class="fl">0.5</span>), calcSSE, <span class="dt">method=</span><span class="st">"SANN"</span>)
<span class="co">#> $par</span>
<span class="co">#> [1] 0.05433545</span>
<span class="co">#> </span>
<span class="co">#> $value</span>
<span class="co">#> [1] 3.85753e-28</span>
<span class="co">#> </span>
<span class="co">#> $counts</span>
<span class="co">#> function gradient </span>
<span class="co">#> 10000 NA </span>
<span class="co">#> </span>
<span class="co">#> $convergence</span>
<span class="co">#> [1] 0</span>
<span class="co">#> </span>
<span class="co">#> $message</span>
<span class="co">#> NULL</span></code></pre></div>
<p>For this case, the best value of <code>span</code> turns out to be <code>0.05433</code> and the minimum SSE achieved is <code>3.85e-28</code>.</p>
</div>
</div>
<div class="footer">
<hr>
<p>© 2016-17 Selva Prabhakaran. Powered by <a href="http://jekyllrb.com/">jekyll</a>,
<a href="http://yihui.name/knitr/">knitr</a>, and
<a href="http://johnmacfarlane.net/pandoc/">pandoc</a>.
This work is licensed under the <a href="http://creativecommons.org/licenses/by-nc/3.0/">Creative Commons License.</a>
</p>
</div>
</div> <!-- /container -->
<script src="//code.jquery.com/jquery.js"></script>
<script src="www/bootstrap.min.js"></script>
<script src="www/toc.js"></script>
<!-- MathJax Script -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}
});
</script>
<script type="text/javascript"
src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<!-- Google Analytics Code -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-69351797-1', 'auto');
ga('send', 'pageview');
</script>
<style type="text/css">
/* reduce spacing around math formula*/
.MathJax_Display {
margin: 0em 0em;
}
body {
font-family: 'Helvetica Neue', Roboto, Arial, sans-serif;
font-size: 16px;
line-height: 27px;
font-weight: 400;
}
blockquote p {
line-height: 1.75;
color: #717171;
}
.well li{
line-height: 28px;
}
li.dropdown-header {
display: block;
padding: 0px;
font-size: 14px;
}
</style>
</body>
</html>