forked from brianstock/spatial-bycatch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
2_run_models.html
610 lines (554 loc) · 57.2 KB
/
2_run_models.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="Brian Stock" />
<title>Step 2: Run spatiotemporal models for fisheries bycatch prediction</title>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
div.sourceCode { overflow-x: auto; }
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; line-height: 100%; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
code > span.kw { color: #007020; font-weight: bold; } /* Keyword */
code > span.dt { color: #902000; } /* DataType */
code > span.dv { color: #40a070; } /* DecVal */
code > span.bn { color: #40a070; } /* BaseN */
code > span.fl { color: #40a070; } /* Float */
code > span.ch { color: #4070a0; } /* Char */
code > span.st { color: #4070a0; } /* String */
code > span.co { color: #60a0b0; font-style: italic; } /* Comment */
code > span.ot { color: #007020; } /* Other */
code > span.al { color: #ff0000; font-weight: bold; } /* Alert */
code > span.fu { color: #06287e; } /* Function */
code > span.er { color: #ff0000; font-weight: bold; } /* Error */
code > span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
code > span.cn { color: #880000; } /* Constant */
code > span.sc { color: #4070a0; } /* SpecialChar */
code > span.vs { color: #4070a0; } /* VerbatimString */
code > span.ss { color: #bb6688; } /* SpecialString */
code > span.im { } /* Import */
code > span.va { color: #19177c; } /* Variable */
code > span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code > span.op { color: #666666; } /* Operator */
code > span.bu { } /* BuiltIn */
code > span.ex { } /* Extension */
code > span.pp { color: #bc7a00; } /* Preprocessor */
code > span.at { color: #7d9029; } /* Attribute */
code > span.do { color: #ba2121; font-style: italic; } /* Documentation */
code > span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code > span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code > span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
</style>
<link href="data:text/css;charset=utf-8,body%20%7B%0Abackground%2Dcolor%3A%20%23fff%3B%0Amargin%3A%201em%20auto%3B%0Amax%2Dwidth%3A%20700px%3B%0Aoverflow%3A%20visible%3B%0Apadding%2Dleft%3A%202em%3B%0Apadding%2Dright%3A%202em%3B%0Afont%2Dfamily%3A%20%22Open%20Sans%22%2C%20%22Helvetica%20Neue%22%2C%20Helvetica%2C%20Arial%2C%20sans%2Dserif%3B%0Afont%2Dsize%3A%2014px%3B%0Aline%2Dheight%3A%201%2E35%3B%0A%7D%0A%23header%20%7B%0Atext%2Dalign%3A%20center%3B%0A%7D%0A%23TOC%20%7B%0Aclear%3A%20both%3B%0Amargin%3A%200%200%2010px%2010px%3B%0Apadding%3A%204px%3B%0Awidth%3A%20400px%3B%0Aborder%3A%201px%20solid%20%23CCCCCC%3B%0Aborder%2Dradius%3A%205px%3B%0Abackground%2Dcolor%3A%20%23f6f6f6%3B%0Afont%2Dsize%3A%2013px%3B%0Aline%2Dheight%3A%201%2E3%3B%0A%7D%0A%23TOC%20%2Etoctitle%20%7B%0Afont%2Dweight%3A%20bold%3B%0Afont%2Dsize%3A%2015px%3B%0Amargin%2Dleft%3A%205px%3B%0A%7D%0A%23TOC%20ul%20%7B%0Apadding%2Dleft%3A%2040px%3B%0Amargin%2Dleft%3A%20%2D1%2E5em%3B%0Amargin%2Dtop%3A%205px%3B%0Amargin%2Dbottom%3A%205px%3B%0A%7D%0A%23TOC%20ul%20ul%20%7B%0Amargin%2Dleft%3A%20%2D2em%3B%0A%7D%0A%23TOC%20li%20%7B%0Aline%2Dheight%3A%2016px%3B%0A%7D%0Atable%20%7B%0Amargin%3A%201em%20auto%3B%0Aborder%2Dwidth%3A%201px%3B%0Aborder%2Dcolor%3A%20%23DDDDDD%3B%0Aborder%2Dstyle%3A%20outset%3B%0Aborder%2Dcollapse%3A%20collapse%3B%0A%7D%0Atable%20th%20%7B%0Aborder%2Dwidth%3A%202px%3B%0Apadding%3A%205px%3B%0Aborder%2Dstyle%3A%20inset%3B%0A%7D%0Atable%20td%20%7B%0Aborder%2Dwidth%3A%201px%3B%0Aborder%2Dstyle%3A%20inset%3B%0Aline%2Dheight%3A%2018px%3B%0Apadding%3A%205px%205px%3B%0A%7D%0Atable%2C%20table%20th%2C%20table%20td%20%7B%0Aborder%2Dleft%2Dstyle%3A%20none%3B%0Aborder%2Dright%2Dstyle%3A%20none%3B%0A%7D%0Atable%20thead%2C%20table%20tr%2Eeven%20%7B%0Abackground%2Dcolor%3A%20%23f7f7f7%3B%0A%7D%0Ap%20%7B%0Amargin%3A%200%2E5em%200%3B%0A%7D%0Ablockquote%20%7B%0Abackground%2Dcolor%3A%20%23f6f6f6%3B%0Apadding%3A%200%2E25em%200%2E75em%3B%0A%7D%0Ahr%20%7B%0Aborder%2Dstyle%3A%20solid%3B%0Aborder%3A%20none%3B%0Aborder%2Dtop%3A%201px%20solid%20%23777%3B%0Amargin%3A%2028px%200%3B%0A%7D%0Adl%20%7B%0Amargin%2Dleft%3A%200%3B%0A%7D%0Adl%20dd%20%7B%0Amargin%2Dbottom%3A%2013px%3B%0Amargin%2Dleft%3A%2013px%3B%0A%7D%0Adl%20dt%20%7B%0Afont%2Dweight%3A%20bold%3B%0A%7D%0Aul%20%7B%0Amargin%2Dtop%3A%200%3B%0A%7D%0Aul%20li%20%7B%0Alist%2Dstyle%3A%20circle%20outside%3B%0A%7D%0Aul%20ul%20%7B%0Amargin%2Dbottom%3A%200%3B%0A%7D%0Apre%2C%20code%20%7B%0Abackground%2Dcolor%3A%20%23f7f7f7%3B%0Aborder%2Dradius%3A%203px%3B%0Acolor%3A%20%23333%3B%0Awhite%2Dspace%3A%20pre%2Dwrap%3B%20%0A%7D%0Apre%20%7B%0Aborder%2Dradius%3A%203px%3B%0Amargin%3A%205px%200px%2010px%200px%3B%0Apadding%3A%2010px%3B%0A%7D%0Apre%3Anot%28%5Bclass%5D%29%20%7B%0Abackground%2Dcolor%3A%20%23f7f7f7%3B%0A%7D%0Acode%20%7B%0Afont%2Dfamily%3A%20Consolas%2C%20Monaco%2C%20%27Courier%20New%27%2C%20monospace%3B%0Afont%2Dsize%3A%2085%25%3B%0A%7D%0Ap%20%3E%20code%2C%20li%20%3E%20code%20%7B%0Apadding%3A%202px%200px%3B%0A%7D%0Adiv%2Efigure%20%7B%0Atext%2Dalign%3A%20center%3B%0A%7D%0Aimg%20%7B%0Abackground%2Dcolor%3A%20%23FFFFFF%3B%0Apadding%3A%202px%3B%0Aborder%3A%201px%20solid%20%23DDDDDD%3B%0Aborder%2Dradius%3A%203px%3B%0Aborder%3A%201px%20solid%20%23CCCCCC%3B%0Amargin%3A%200%205px%3B%0A%7D%0Ah1%20%7B%0Amargin%2Dtop%3A%200%3B%0Afont%2Dsize%3A%2035px%3B%0Aline%2Dheight%3A%2040px%3B%0A%7D%0Ah2%20%7B%0Aborder%2Dbottom%3A%204px%20solid%20%23f7f7f7%3B%0Apadding%2Dtop%3A%2010px%3B%0Apadding%2Dbottom%3A%202px%3B%0Afont%2Dsize%3A%20145%25%3B%0A%7D%0Ah3%20%7B%0Aborder%2Dbottom%3A%202px%20solid%20%23f7f7f7%3B%0Apadding%2Dtop%3A%2010px%3B%0Afont%2Dsize%3A%20120%25%3B%0A%7D%0Ah4%20%7B%0Aborder%2Dbottom%3A%201px%20solid%20%23f7f7f7%3B%0Amargin%2Dleft%3A%208px%3B%0Afont%2Dsize%3A%20105%25%3B%0A%7D%0Ah5%2C%20h6%20%7B%0Aborder%2Dbottom%3A%201px%20solid%20%23ccc%3B%0Afont%2Dsize%3A%20105%25%3B%0A%7D%0Aa%20%7B%0Acolor%3A%20%230033dd%3B%0Atext%2Ddecoration%3A%20none%3B%0A%7D%0Aa%3Ahover%20%7B%0Acolor%3A%20%236666ff%3B%20%7D%0Aa%3Avisited%20%7B%0Acolor%3A%20%23800080%3B%20%7D%0Aa%3Avisited%3Ahover%20%7B%0Acolor%3A%20%23BB00BB%3B%20%7D%0Aa%5Bhref%5E%3D%22http%3A%22%5D%20%7B%0Atext%2Ddecoration%3A%20underline%3B%20%7D%0Aa%5Bhref%5E%3D%22https%3A%22%5D%20%7B%0Atext%2Ddecoration%3A%20underline%3B%20%7D%0A%0Acode%20%3E%20span%2Ekw%20%7B%20color%3A%20%23555%3B%20font%2Dweight%3A%20bold%3B%20%7D%20%0Acode%20%3E%20span%2Edt%20%7B%20color%3A%20%23902000%3B%20%7D%20%0Acode%20%3E%20span%2Edv%20%7B%20color%3A%20%2340a070%3B%20%7D%20%0Acode%20%3E%20span%2Ebn%20%7B%20color%3A%20%23d14%3B%20%7D%20%0Acode%20%3E%20span%2Efl%20%7B%20color%3A%20%23d14%3B%20%7D%20%0Acode%20%3E%20span%2Ech%20%7B%20color%3A%20%23d14%3B%20%7D%20%0Acode%20%3E%20span%2Est%20%7B%20color%3A%20%23d14%3B%20%7D%20%0Acode%20%3E%20span%2Eco%20%7B%20color%3A%20%23888888%3B%20font%2Dstyle%3A%20italic%3B%20%7D%20%0Acode%20%3E%20span%2Eot%20%7B%20color%3A%20%23007020%3B%20%7D%20%0Acode%20%3E%20span%2Eal%20%7B%20color%3A%20%23ff0000%3B%20font%2Dweight%3A%20bold%3B%20%7D%20%0Acode%20%3E%20span%2Efu%20%7B%20color%3A%20%23900%3B%20font%2Dweight%3A%20bold%3B%20%7D%20%20code%20%3E%20span%2Eer%20%7B%20color%3A%20%23a61717%3B%20background%2Dcolor%3A%20%23e3d2d2%3B%20%7D%20%0A" rel="stylesheet" type="text/css" />
</head>
<body>
<h1 class="title toc-ignore">Step 2: Run spatiotemporal models for fisheries bycatch prediction</h1>
<h4 class="author"><em>Brian Stock</em></h4>
<h4 class="date"><em>Sept 29, 2017</em></h4>
<p>This vignette demonstrates how we ran the spatiotemporal models in:</p>
<blockquote>
<p>Stock BC, Ward EJ, Eguchi T, Jannot JE, Thorson JT, Feist BE, and Semmens BX. “Random forests outperform other species distribution models for spatiotemporal fisheries bycatch prediction.”</p>
</blockquote>
<ul>
<li><a href="#GLM">GLM</a></li>
<li><a href="#GAM_const">GAM CONSTANT (one spatial field)</a></li>
<li><a href="#GAM_iid">GAM IID (spatial field by year)</a></li>
<li><a href="#GMRF_const">GMRF CONSTANT (one spatial field)</a></li>
<li><a href="#GMRF_iid">GMRF EXCHANGEABLE (spatial field by year)</a></li>
<li><a href="#RF_base">RF BASE</a></li>
<li><a href="#RF_down">RF DOWN (downsample)</a></li>
<li><a href="#RF_smote">RF SMOTE (upsample + downsample)</a></li>
</ul>
<p>We assume you either 1) have already seen <a href="https://rawgit.com/brianstock/spatial-bycatch/master/2a_process_survey.html"><code>1_process_survey</code></a>, or 2) are not interested in how the data were processed/prepared. Either way, from this point we continue by using the saved output of <code>1_process_survey</code> (<code>wcann_processed.RData</code>).</p>
<p><em>Note:</em> Because the fisheries observer datasets we used are confidential (<a href="https://www.nwfsc.noaa.gov/research/divisions/fram/observation/data_collection/manuals/2017%20WCGOP%20Training%20Manual%20Final%20website%20copy.pdf">WCGOP</a>, <a href="http://www.nmfs.noaa.gov/pr/interactions/fkwtrt/meeting1/handouts/observer_manual.pdf">HILL</a>), here we perform the same analyses using the publically available <a href="https://www.nwfsc.noaa.gov/research/divisions/fram/groundfish/bottom_trawl.cfm">West Coast Groundfish Trawl Survey</a>.</p>
<div id="load-data-and-packages" class="section level3">
<h3>Load data and packages</h3>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># load the data from 1_process_survey</span>
<span class="kw">load</span>(<span class="st">"/home/brian/Dropbox/bycatch/manuscript/spatial-bycatch/wcann_processed.RData"</span>)
<span class="kw">head</span>(dat)</code></pre></div>
<pre><code>## HAUL_ID YEAR DATE LAT LON DEPTH TOTAL DBRK
## 359 2.00303e+11 2003 2003-06-24 46.09611 -124.7761 564.9317 123.176 0.00
## 6671 2.00303e+11 2003 2003-06-24 46.02472 -124.7389 310.0056 304.980 1.81
## 6925 2.00303e+11 2003 2003-06-24 46.15667 -124.5156 140.7280 501.270 1.35
## 6926 2.00303e+11 2003 2003-06-24 46.50389 -124.7325 606.3237 98.910 0.00
## 7216 2.00303e+11 2003 2003-06-24 46.75500 -124.5428 107.4615 714.960 0.00
## 182 2.00303e+11 2003 2003-06-25 47.60194 -124.8156 106.0853 573.350 0.10
## PHLB YEYE DAY YEYE_01 PHLB_01 DBRK_01 SST fath
## 359 0 0 -43.1275 0 0 0 -0.01410765 308.90841
## 6671 0 0 -43.1275 0 0 1 0.04703642 169.51312
## 6925 18 0 -43.1275 0 1 1 -0.06884963 76.95101
## 6926 0 0 -43.1275 0 0 0 -0.38681021 331.54183
## 7216 0 0 -43.1275 0 0 0 -0.61593420 58.76066
## 182 0 0 -42.1275 0 0 1 -1.53736698 58.00815
## fath_categ id MONTH inRCA bin logDEPTH sst sst2
## 359 250+ 1 Jun 0 0 0.7985194 0.8565284 0.73364093
## 6671 150-200 2 Jun 1 4 0.1984049 0.9176725 0.84212280
## 6925 75-100 3 Jun 1 4 -0.5913565 0.8017864 0.64286150
## 6926 250+ 4 Jun 0 0 0.8692286 0.4838259 0.23408747
## 7216 50-60 5 Jun 1 4 -0.8610528 0.2547019 0.06487305
## 182 50-60 6 Jun 1 4 -0.8739419 -0.6667309 0.44453010
## logDEPTH2
## 359 0.63763326
## 6671 0.03936452
## 6925 0.34970247
## 6926 0.75555833
## 7216 0.74141188
## 182 0.76377450</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(randomForest)
<span class="kw">library</span>(ROCR)
<span class="kw">library</span>(DMwR)
<span class="kw">library</span>(caret)
<span class="kw">library</span>(mgcv)
<span class="kw">library</span>(INLA)
<span class="co"># INLA:::inla.dynload.workaround() # if old dependencies</span></code></pre></div>
</div>
<div id="setup-stratified-10-fold-cross-validation" class="section level3">
<h3>Setup stratified 10-fold cross validation</h3>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Use caret package to do stratified k-fold cross validation</span>
k =<span class="st"> </span><span class="dv">10</span>
ind <-<span class="st"> </span><span class="kw">list</span>()
species.bin <-<span class="st"> </span><span class="kw">c</span>(<span class="st">"DBRK"</span>,<span class="st">"PHLB"</span>,<span class="st">"YEYE"</span>)
for(sp in <span class="dv">1</span>:<span class="kw">length</span>(species.bin)){
sp.col <-<span class="st"> </span><span class="kw">paste0</span>(species.bin[sp],<span class="st">"_01"</span>)
ind[[sp]] <-<span class="st"> </span><span class="kw">createFolds</span>(dat[,sp.col], <span class="dt">k=</span>k)
}</code></pre></div>
</div>
<div id="functions-to-calculate-model-performance" class="section level3">
<h3>Functions to calculate model performance</h3>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">calc_AUC <-<span class="st"> </span>function(pred, obs){
obs <-<span class="st"> </span><span class="kw">as.numeric</span>(<span class="kw">as.character</span>(obs))
predict =<span class="st"> </span><span class="kw">prediction</span>(<span class="kw">as.vector</span>(pred), obs)
AUC <-<span class="st"> </span><span class="kw">round</span>(<span class="kw">unlist</span>(<span class="kw">slot</span>(<span class="kw">performance</span>(predict,<span class="st">"auc"</span>),<span class="st">"y.values"</span>)),<span class="dv">3</span>)
<span class="kw">return</span>(AUC)
}
calc_RMSE <-<span class="st"> </span>function(pred, obs){
RMSE <-<span class="st"> </span><span class="kw">round</span>(<span class="kw">sqrt</span>(<span class="kw">mean</span>((pred-obs)^<span class="dv">2</span>)),<span class="dv">3</span>)
<span class="kw">return</span>(RMSE)
}</code></pre></div>
</div>
<div id="model-descriptions-and-functions" class="section level3">
<h3>Model descriptions and functions</h3>
<p><span class="math inline">\(Y\)</span> is the response:</p>
<ul>
<li>0/1 for the binomial component of delta model</li>
<li>catch (kg) for the positive component of delta model</li>
</ul>
<p><span class="math inline">\(Y_j\)</span> denotes response in year <span class="math inline">\(j\)</span> for models that fit spatial terms by year.</p>
<div id="GLM" class="section level6">
<h6>1. GLM</h6>
<blockquote>
<p><span class="math inline">\(Y\)</span> ~ logDEPTH + logDEPTH<span class="math inline">\(^2\)</span> + sst + sst<span class="math inline">\(^2\)</span> + inRCA + DAY + YEAR</p>
</blockquote>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">fit_GLM <-<span class="st"> </span>function(dat, sp.ind, covar, modeltype, fit.id, test.id){
btime <-<span class="st"> </span><span class="kw">Sys.time</span>()
dat$z <-<span class="st"> </span>dat[,sp.ind]
formula.glm =<span class="st"> </span><span class="kw">as.formula</span>(<span class="kw">paste0</span>(<span class="st">"z ~ -1 + YEAR + "</span>, <span class="kw">paste</span>(covar, <span class="dt">collapse=</span><span class="st">" + "</span>)))
if(modeltype==<span class="st">"binomial"</span>) fit <-<span class="st"> </span><span class="kw">gam</span>(formula.glm, <span class="dt">family=</span><span class="st">"binomial"</span>, <span class="dt">data=</span>dat[fit.id,])
if(modeltype==<span class="st">"positive"</span>) fit <-<span class="st"> </span><span class="kw">gam</span>(formula.glm, <span class="dt">family=</span><span class="kw">Gamma</span>(<span class="dt">link=</span><span class="st">"log"</span>), <span class="dt">data=</span>dat[fit.id,])
<span class="co"># calculate and return performance</span>
obs <-<span class="st"> </span>dat[test.id, sp.ind] <span class="co"># observations at test locations</span>
pred <-<span class="st"> </span><span class="kw">predict</span>(fit, <span class="dt">newdata=</span>dat[test.id,], <span class="dt">type=</span><span class="st">'response'</span>)
etime <-<span class="st"> </span><span class="kw">Sys.time</span>()
rtime <-<span class="st"> </span>etime -<span class="st"> </span>btime
if(modeltype==<span class="st">"binomial"</span>){
AUC <-<span class="st"> </span><span class="kw">calc_AUC</span>(pred, obs)
<span class="kw">return</span>(<span class="kw">list</span>(AUC, fit, pred, obs, rtime))
}
if(modeltype==<span class="st">"positive"</span>){
RMSE <-<span class="st"> </span><span class="kw">calc_RMSE</span>(pred, obs)
<span class="kw">return</span>(<span class="kw">list</span>(RMSE, fit, pred, obs, rtime))
}
}</code></pre></div>
</div>
<div id="GAM_const" class="section level6">
<h6>2. GAM CONSTANT</h6>
<blockquote>
<p><span class="math inline">\(Y\)</span> ~ logDEPTH + logDEPTH<span class="math inline">\(^2\)</span> + sst + sst<span class="math inline">\(^2\)</span> + inRCA + DAY + YEAR + s(LON, LAT)</p>
</blockquote>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">fit_GAM_CONSTANT <-<span class="st"> </span>function(dat, sp.ind, covar, modeltype, fit.id, test.id){
btime <-<span class="st"> </span><span class="kw">Sys.time</span>()
dat$z <-<span class="st"> </span>dat[,sp.ind]
formula.gam.const =<span class="st"> </span><span class="kw">as.formula</span>(<span class="kw">paste0</span>(<span class="st">"z ~ -1 + YEAR + s(LON,LAT,k=100) + "</span>,
<span class="kw">paste</span>(covar, <span class="dt">collapse=</span><span class="st">" + "</span>)))
if(modeltype==<span class="st">"binomial"</span>) fit <-<span class="st"> </span><span class="kw">gam</span>(formula.gam.const, <span class="dt">family=</span><span class="st">"binomial"</span>, <span class="dt">data=</span>dat[fit.id,])
if(modeltype==<span class="st">"positive"</span>) fit <-<span class="st"> </span><span class="kw">gam</span>(formula.gam.const, <span class="dt">family=</span><span class="kw">Gamma</span>(<span class="dt">link=</span><span class="st">"log"</span>), <span class="dt">data=</span>dat[fit.id,])
<span class="co"># calculate and return performance</span>
obs <-<span class="st"> </span>dat[test.id, sp.ind] <span class="co"># observations at test locations</span>
pred <-<span class="st"> </span><span class="kw">predict</span>(fit, <span class="dt">newdata=</span>dat[test.id,], <span class="dt">type=</span><span class="st">'response'</span>)
etime <-<span class="st"> </span><span class="kw">Sys.time</span>()
rtime <-<span class="st"> </span>etime -<span class="st"> </span>btime
if(modeltype==<span class="st">"binomial"</span>){
AUC <-<span class="st"> </span><span class="kw">calc_AUC</span>(pred, obs)
<span class="kw">return</span>(<span class="kw">list</span>(AUC, fit, pred, obs, rtime))
}
if(modeltype==<span class="st">"positive"</span>){
RMSE <-<span class="st"> </span><span class="kw">calc_RMSE</span>(pred, obs)
<span class="kw">return</span>(<span class="kw">list</span>(RMSE, fit, pred, obs, rtime))
}
}</code></pre></div>
</div>
<div id="GAM_iid" class="section level6">
<h6>3. GAM IID</h6>
<blockquote>
<p><span class="math inline">\(Y_j\)</span> ~ logDEPTH + logDEPTH<span class="math inline">\(^2\)</span> + sst + sst<span class="math inline">\(^2\)</span> + inRCA + DAY + s(LON, LAT)<span class="math inline">\(_j\)</span></p>
</blockquote>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">fit_GAM_IID <-<span class="st"> </span>function(dat, sp.ind, covar, modeltype, fit.id, test.id){
btime <-<span class="st"> </span><span class="kw">Sys.time</span>()
dat$z <-<span class="st"> </span>dat[,sp.ind]
formula.gam.iid =<span class="st"> </span><span class="kw">as.formula</span>(<span class="kw">paste0</span>(<span class="st">"z ~ -1 + s(LON,LAT,k=100,by=YEAR) + "</span>, <span class="kw">paste</span>(covar, <span class="dt">collapse=</span><span class="st">" + "</span>)))
if(modeltype==<span class="st">"binomial"</span>) fit <-<span class="st"> </span><span class="kw">gam</span>(formula.gam.iid, <span class="dt">family=</span><span class="st">"binomial"</span>, <span class="dt">data=</span>dat[fit.id,])
if(modeltype==<span class="st">"positive"</span>) fit <-<span class="st"> </span><span class="kw">gam</span>(formula.gam.iid, <span class="dt">family=</span><span class="kw">Gamma</span>(<span class="dt">link=</span><span class="st">"log"</span>), <span class="dt">data=</span>dat[fit.id,])
<span class="co"># calculate and return performance</span>
obs <-<span class="st"> </span>dat[test.id, sp.ind] <span class="co"># observations at test locations</span>
pred <-<span class="st"> </span><span class="kw">predict</span>(fit, <span class="dt">newdata=</span>dat[test.id,], <span class="dt">type=</span><span class="st">'response'</span>)
etime <-<span class="st"> </span><span class="kw">Sys.time</span>()
rtime <-<span class="st"> </span>etime -<span class="st"> </span>btime
if(modeltype==<span class="st">"binomial"</span>){
AUC <-<span class="st"> </span><span class="kw">calc_AUC</span>(pred, obs)
<span class="kw">return</span>(<span class="kw">list</span>(AUC, fit, pred, obs, rtime))
}
if(modeltype==<span class="st">"positive"</span>){
RMSE <-<span class="st"> </span><span class="kw">calc_RMSE</span>(pred, obs)
<span class="kw">return</span>(<span class="kw">list</span>(RMSE, fit, pred, obs, rtime))
}
}</code></pre></div>
</div>
<div id="GMRF_const" class="section level6">
<h6>4. GMRF CONSTANT</h6>
<blockquote>
<p><span class="math inline">\(Y\)</span> ~ logDEPTH + logDEPTH<span class="math inline">\(^2\)</span> + sst + sst<span class="math inline">\(^2\)</span> + inRCA + DAY + YEAR + <span class="math inline">\(MVN(0, Q^{-1})\)</span></p>
</blockquote>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># See below:</span>
<span class="co"># one GMRF function with input option to select CONSTANT vs. EXCHANGEABLE</span></code></pre></div>
</div>
<div id="GMRF_iid" class="section level6">
<h6>5. GMRF EXCHANGEABLE</h6>
<blockquote>
<p><span class="math inline">\(Y_j\)</span> ~ logDEPTH + logDEPTH<span class="math inline">\(^2\)</span> + sst + sst<span class="math inline">\(^2\)</span> + inRCA + DAY + YEAR + <span class="math inline">\(MVN(0, Q_j^{-1})\)</span></p>
</blockquote>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">fit_GMRF <-<span class="st"> </span>function(dat, sp.ind, covar, modeltype, modeltype.GMRF, fit.id, test.id){
btime <-<span class="st"> </span><span class="kw">Sys.time</span>()
<span class="co"># response needs to be numeric, not factor</span>
dat[,sp.ind] <-<span class="st"> </span><span class="kw">as.numeric</span>(<span class="kw">as.character</span>(dat[,sp.ind]))
<span class="co"># inRCA needs to be numeric, not factor</span>
dat$inRCA <-<span class="st"> </span><span class="kw">as.numeric</span>(<span class="kw">as.character</span>(dat$inRCA))
<span class="co"># turn 2012 to NA so YEAR=2012 will be intercept, other years will be offsets</span>
if(modeltype.GMRF==<span class="st">"CONSTANT"</span>){
dat$YEAR <-<span class="st"> </span><span class="kw">as.numeric</span>(<span class="kw">as.character</span>(dat$YEAR))
dat$YEAR[<span class="kw">which</span>(dat$YEAR==<span class="dv">2012</span>)] <-<span class="st"> </span><span class="ot">NA</span>
dat$YEAR <-<span class="st"> </span><span class="kw">as.factor</span>(dat$YEAR)
}
<span class="co"># record keeping</span>
n.years <-<span class="st"> </span><span class="kw">length</span>(<span class="kw">levels</span>(dat$YEAR))
yr.labs <-<span class="st"> </span><span class="kw">levels</span>(dat$YEAR)
<span class="kw">levels</span>(dat$YEAR) <-<span class="st"> </span><span class="dv">1</span>:n.years
n.sites <-<span class="st"> </span><span class="kw">dim</span>(dat)[<span class="dv">1</span>]
<span class="co"># CONSTANT includes offset terms for each year</span>
<span class="co"># EXCHANGEABLE includes separate GMRF for each year, so don't want YEAR terms</span>
if(modeltype.GMRF==<span class="st">"CONSTANT"</span>) covar =<span class="st"> </span><span class="kw">c</span>(covar,<span class="st">"YEAR"</span>)
n.covar <-<span class="st"> </span><span class="kw">length</span>(covar)
<span class="co"># difference between binomial and positive delta model components</span>
if(modeltype==<span class="st">"binomial"</span>) family.inla =<span class="st"> "binomial"</span>
if(modeltype==<span class="st">"positive"</span>) family.inla =<span class="st"> "gamma"</span>
n.fit <-<span class="st"> </span><span class="kw">length</span>(fit.id)
n.test <-<span class="st"> </span><span class="kw">length</span>(test.id)
<span class="co"># Set up mesh</span>
coords.fit =<span class="st"> </span><span class="kw">cbind</span>(dat$LON[fit.id], dat$LAT[fit.id])
coords.test =<span class="st"> </span><span class="kw">cbind</span>(dat$LON[test.id], dat$LAT[test.id])
bnd =<span class="st"> </span><span class="kw">inla.nonconvex.hull</span>(coords.fit, <span class="dt">convex=</span>-<span class="fl">0.05</span>, <span class="dt">concave=</span>-<span class="fl">0.2</span>)
mesh1 =<span class="st"> </span><span class="kw">inla.mesh.2d</span>(<span class="dt">loc=</span>coords.fit, <span class="dt">boundary=</span>bnd, <span class="dt">offset=</span><span class="kw">c</span>(-<span class="fl">0.01</span>,-<span class="fl">0.03</span>),
<span class="dt">cutoff=</span><span class="fl">0.3</span>, <span class="dt">max.edge=</span><span class="kw">c</span>(.<span class="dv">6</span>,<span class="fl">1.3</span>))
spde =<span class="st"> </span><span class="kw">inla.spde2.matern</span>(mesh1, <span class="dt">alpha=</span><span class="dv">2</span>) <span class="co"># alpha = matern parameter</span>
<span class="co"># Make index for spatial field</span>
<span class="co"># CONSTANT: fit one spatial field</span>
<span class="co"># EXCHANGEABLE: fit different spatial fields for each year</span>
if(modeltype.GMRF==<span class="st">"CONSTANT"</span>) iset <-<span class="st"> </span><span class="kw">inla.spde.make.index</span>(<span class="st">"i"</span>, <span class="dt">n.spde=</span>mesh1$n)
if(modeltype.GMRF==<span class="st">"EXCHANGEABLE"</span>) iset <-<span class="st"> </span><span class="kw">inla.spde.make.index</span>(<span class="st">'i'</span>, <span class="dt">n.spde=</span>spde$n.spde,
<span class="dt">n.group=</span>n.years)
<span class="co"># Make A matrix (projects from mesh nodes to data locations)</span>
if(modeltype.GMRF==<span class="st">"CONSTANT"</span>){
A <-<span class="st"> </span><span class="kw">inla.spde.make.A</span>(<span class="dt">mesh=</span>mesh1, <span class="dt">loc=</span>coords.fit)
A.test <-<span class="st"> </span><span class="kw">inla.spde.make.A</span>(<span class="dt">mesh=</span>mesh1, <span class="dt">loc=</span>coords.test)
}
if(modeltype.GMRF==<span class="st">"EXCHANGEABLE"</span>){
A <-<span class="st"> </span><span class="kw">inla.spde.make.A</span>(<span class="dt">mesh=</span>mesh1, <span class="dt">loc=</span>coords.fit,
<span class="dt">group=</span><span class="kw">as.numeric</span>(dat$YEAR)[fit.id])
A.test <-<span class="st"> </span><span class="kw">inla.spde.make.A</span>(<span class="dt">mesh=</span>mesh1, <span class="dt">loc=</span>coords.test,
<span class="dt">group=</span><span class="kw">as.numeric</span>(dat$YEAR)[test.id])
}
A.list =<span class="st"> </span><span class="kw">list</span>(); A.list[[<span class="dv">1</span>]] =<span class="st"> </span>A;
for(i in <span class="dv">1</span>:n.covar) A.list[[i<span class="dv">+1</span>]] <-<span class="st"> </span><span class="dv">1</span>;
A.list.test =<span class="st"> </span><span class="kw">list</span>(); A.list.test[[<span class="dv">1</span>]] =<span class="st"> </span>A.test;
for (i in <span class="dv">1</span>:n.covar) A.list.test[[i<span class="dv">+1</span>]] <-<span class="st"> </span><span class="dv">1</span>;
<span class="co"># Make list of covariates including 'iset', the GMRF</span>
effect.list =<span class="st"> </span><span class="kw">list</span>(<span class="dt">i =</span> iset,
<span class="dt">sst =</span> dat[fit.id,<span class="st">"sst"</span>],
<span class="dt">sst2 =</span> dat[fit.id,<span class="st">"sst2"</span>],
<span class="dt">logDEPTH =</span> dat[fit.id,<span class="st">"logDEPTH"</span>],
<span class="dt">logDEPTH2 =</span> dat[fit.id,<span class="st">"logDEPTH2"</span>],
<span class="dt">inRCA =</span> dat[fit.id,<span class="st">"inRCA"</span>],
<span class="dt">DAY =</span> dat[fit.id,<span class="st">"DAY"</span>])
effect.list.test =<span class="st"> </span><span class="kw">list</span>(<span class="dt">i =</span> iset,
<span class="dt">sst =</span> dat[test.id,<span class="st">"sst"</span>],
<span class="dt">sst2 =</span> dat[test.id,<span class="st">"sst2"</span>],
<span class="dt">logDEPTH =</span> dat[test.id,<span class="st">"logDEPTH"</span>],
<span class="dt">logDEPTH2 =</span> dat[test.id,<span class="st">"logDEPTH2"</span>],
<span class="dt">inRCA =</span> dat[test.id,<span class="st">"inRCA"</span>],
<span class="dt">DAY =</span> dat[test.id,<span class="st">"DAY"</span>])
if(modeltype.GMRF==<span class="st">"CONSTANT"</span>){ <span class="co"># CONSTANT model has YEAR terms in it</span>
effect.list$YEAR <-<span class="st"> </span>dat[fit.id,<span class="st">"YEAR"</span>]
effect.list.test$YEAR <-<span class="st"> </span>dat[test.id,<span class="st">"YEAR"</span>]
}
<span class="co"># 'stack' data together</span>
<span class="co"># sdat.fit: data for GMRF model to fit</span>
sdat.fit <-<span class="st"> </span><span class="kw">inla.stack</span>(<span class="dt">tag=</span><span class="st">'sdat.fit'</span>, <span class="dt">data=</span><span class="kw">list</span>(<span class="dt">z=</span>dat[fit.id, sp.ind]),
<span class="dt">A=</span>A.list, <span class="dt">effects=</span>effect.list)
<span class="co"># sdat.test: data for GMRF model to predict</span>
<span class="co"># set z=NA to tell R-INLA to predict for these locations</span>
sdat.test <-<span class="st"> </span><span class="kw">inla.stack</span>(<span class="dt">tag=</span><span class="st">'sdat.test'</span>, <span class="dt">data=</span><span class="kw">list</span>(<span class="dt">z=</span><span class="kw">rep</span>(<span class="ot">NA</span>, n.test)),
<span class="dt">A=</span>A.list.test, <span class="dt">effects=</span>effect.list.test)
sdat.full <-<span class="st"> </span><span class="kw">inla.stack</span>(sdat.fit, sdat.test)
<span class="co"># Make INLA formula</span>
if(modeltype.GMRF==<span class="st">"CONSTANT"</span>){
formula.inla =<span class="st"> </span><span class="kw">as.formula</span>(<span class="kw">paste0</span>(<span class="st">"z ~ -1 + "</span>,
<span class="kw">paste</span>(covar, <span class="dt">collapse=</span><span class="st">"+"</span>),
<span class="st">"+ f(i, model=spde)"</span>))}
if(modeltype.GMRF==<span class="st">"EXCHANGEABLE"</span>){
formula.inla =<span class="st"> </span><span class="kw">as.formula</span>(<span class="kw">paste0</span>(<span class="st">"z ~ -1 + "</span>,
<span class="kw">paste</span>(covar, <span class="dt">collapse=</span><span class="st">"+"</span>),
<span class="st">"+ f(i, model=spde, group=i.group, control.group=list(model='exchangeable'))"</span>))}
<span class="co"># Call INLA</span>
<span class="co"># quick run to find posterior mode, using gaussian approximation and </span>
<span class="co"># empirical Bayes integration strategy over the hyperparameters</span>
start.inla <-<span class="st"> </span><span class="kw">inla</span>(formula.inla, <span class="dt">num.threads=</span><span class="dv">12</span>, <span class="dt">family =</span> family.inla,
<span class="dt">data =</span> <span class="kw">inla.stack.data</span>(sdat.full),
<span class="dt">control.predictor =</span> <span class="kw">list</span>(<span class="dt">link=</span><span class="dv">1</span>, <span class="dt">compute=</span><span class="ot">FALSE</span>, <span class="dt">A=</span><span class="kw">inla.stack.A</span>(sdat.full)),
<span class="dt">verbose =</span> <span class="ot">TRUE</span>, <span class="dt">debug=</span><span class="ot">TRUE</span>, <span class="dt">keep=</span><span class="ot">FALSE</span>,
<span class="dt">control.inla =</span> <span class="kw">list</span>(<span class="dt">strategy=</span><span class="st">"gaussian"</span>, <span class="dt">int.strategy=</span><span class="st">"eb"</span>),
<span class="dt">control.compute =</span> <span class="kw">list</span>(<span class="dt">dic=</span><span class="ot">TRUE</span>, <span class="dt">cpo=</span><span class="ot">TRUE</span>),
<span class="dt">control.fixed =</span> <span class="kw">list</span>(<span class="dt">expand.factor.strategy=</span><span class="st">'inla'</span>, <span class="dt">correlation.matrix=</span><span class="ot">TRUE</span>),
<span class="dt">control.results=</span><span class="kw">list</span>(<span class="dt">return.marginals.random=</span><span class="ot">FALSE</span>,<span class="dt">return.marginals.predictor=</span><span class="ot">FALSE</span>))
<span class="co"># longer run using more accurate approximation, uses posterior mode found in previous step</span>
out.inla <-<span class="st"> </span><span class="kw">inla</span>(formula.inla, <span class="dt">num.threads=</span><span class="dv">12</span>, <span class="dt">family =</span> family.inla,
<span class="dt">data=</span><span class="kw">inla.stack.data</span>(sdat.full),
<span class="dt">control.predictor=</span><span class="kw">list</span>(<span class="dt">link=</span><span class="dv">1</span>, <span class="dt">compute=</span><span class="ot">TRUE</span>, <span class="dt">A=</span><span class="kw">inla.stack.A</span>(sdat.full)),
<span class="dt">verbose =</span> <span class="ot">TRUE</span>, <span class="dt">debug=</span><span class="ot">TRUE</span>, <span class="dt">keep=</span><span class="ot">FALSE</span>,
<span class="dt">control.compute =</span> <span class="kw">list</span>(<span class="dt">dic=</span><span class="ot">TRUE</span>,<span class="dt">cpo=</span><span class="ot">TRUE</span>),
<span class="dt">control.fixed =</span> <span class="kw">list</span>(<span class="dt">expand.factor.strategy=</span><span class="st">'inla'</span>,<span class="dt">correlation.matrix=</span><span class="ot">TRUE</span>),
<span class="dt">control.mode =</span> <span class="kw">list</span>(<span class="dt">theta=</span>start.inla$mode$theta, <span class="dt">restart=</span><span class="ot">FALSE</span>),
<span class="dt">control.results=</span><span class="kw">list</span>(<span class="dt">return.marginals.random=</span><span class="ot">FALSE</span>,<span class="dt">return.marginals.predictor=</span><span class="ot">FALSE</span>))
etime <-<span class="st"> </span><span class="kw">Sys.time</span>()
rtime <-<span class="st"> </span>etime -<span class="st"> </span>btime
<span class="co"># Calculate and return performance metrics on test data (binomial)</span>
if(modeltype==<span class="st">"binomial"</span>){
<span class="co"># Get predicted and observed</span>
ind.pred <-<span class="st"> </span><span class="kw">inla.stack.index</span>(sdat.full,<span class="st">'sdat.test'</span>)$data
pred <-<span class="st"> </span>out.inla$summary.fitted.values[ind.pred,<span class="st">"mean"</span>]
obs <-<span class="st"> </span>dat[test.id, sp.ind]
AUC <-<span class="st"> </span><span class="kw">calc_AUC</span>(pred, obs)
<span class="co"># Return AUC and model objects</span>
fit <-<span class="st"> </span><span class="kw">list</span>(<span class="st">"AUC"</span>=AUC,<span class="st">"out.inla"</span>=out.inla,<span class="st">"pred"</span>=pred,<span class="st">"obs"</span>=obs,<span class="st">"rtime"</span>=rtime,<span class="st">"mesh1"</span>=mesh1,
<span class="st">"iset"</span>=iset,<span class="st">"sdat.full"</span>=sdat.full,<span class="st">"test.id"</span>=test.id,<span class="st">"fit.id"</span>=fit.id,
<span class="st">"n.test"</span>=n.test,<span class="st">"n.fit"</span>=n.fit)
}
<span class="co"># Calculate and return performance metrics (positive)</span>
if(modeltype==<span class="st">"positive"</span>){
<span class="co"># Get predicted and observed</span>
ind.pred <-<span class="st"> </span><span class="kw">inla.stack.index</span>(sdat.full,<span class="st">'sdat.test'</span>)$data
pred <-<span class="st"> </span>out.inla$summary.fitted.values[ind.pred,<span class="st">"mean"</span>]
obs <-<span class="st"> </span>dat[test.id, sp.ind]
RMSE <-<span class="st"> </span><span class="kw">calc_RMSE</span>(pred, obs)
<span class="co"># Return RMSE and model objects</span>
fit <-<span class="st"> </span><span class="kw">list</span>(<span class="st">"RMSE"</span>=RMSE,<span class="st">"out.inla"</span>=out.inla,<span class="st">"pred"</span>=pred,<span class="st">"obs"</span>=obs,<span class="st">"rtime"</span>=rtime,
<span class="st">"mesh1"</span>=mesh1,<span class="st">"iset"</span>=iset,<span class="st">"sdat.full"</span>=sdat.full,<span class="st">"test.id"</span>=test.id,
<span class="st">"fit.id"</span>=fit.id,<span class="st">"n.test"</span>=n.test,<span class="st">"n.fit"</span>=n.fit)
}
<span class="kw">return</span>(fit)
}</code></pre></div>
</div>
<div id="RF_base" class="section level6">
<h6>6. RF BASE</h6>
<blockquote>
<p><span class="math inline">\(Y\)</span> ~ logDEPTH, sst, inRCA, DAY, YEAR, LAT, LON</p>
</blockquote>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># RF BASE is the default randomForest function</span>
fit_RF_BASE <-<span class="st"> </span>function(dat, sp.ind, covar, modeltype, fit.id, test.id){
btime <-<span class="st"> </span><span class="kw">Sys.time</span>()
<span class="co"># keep forest for prediction at test locations</span>
fit <-<span class="st"> </span><span class="kw">randomForest</span>(<span class="dt">x=</span>dat[fit.id, covar], <span class="dt">y=</span>dat[fit.id, sp.ind],
<span class="dt">xtest=</span>dat[test.id, covar], <span class="dt">ytest=</span>dat[test.id, sp.ind],
<span class="dt">mtry=</span><span class="dv">3</span>, <span class="dt">ntree=</span><span class="dv">1000</span>, <span class="dt">importance=</span><span class="ot">FALSE</span>, <span class="dt">do.trace=</span><span class="dv">250</span>, <span class="dt">keep.forest=</span><span class="ot">TRUE</span>)
<span class="co"># calculate and return performance</span>
etime <-<span class="st"> </span><span class="kw">Sys.time</span>()
rtime <-<span class="st"> </span>etime -<span class="st"> </span>btime
obs <-<span class="st"> </span>dat[test.id, sp.ind] <span class="co"># observations at test locations</span>
if(modeltype==<span class="st">"binomial"</span>){
pred <-<span class="st"> </span><span class="kw">predict</span>(fit, <span class="dt">newdata=</span>dat[test.id,], <span class="dt">type=</span><span class="st">'prob'</span>)[,<span class="dv">2</span>]
AUC <-<span class="st"> </span><span class="kw">calc_AUC</span>(pred, obs)
<span class="kw">return</span>(<span class="kw">list</span>(AUC, fit, pred, obs, rtime))
}
if(modeltype==<span class="st">"positive"</span>){
pred <-<span class="st"> </span><span class="kw">predict</span>(fit, <span class="dt">newdata=</span>dat[test.id,], <span class="dt">type=</span><span class="st">'response'</span>)
RMSE <-<span class="st"> </span><span class="kw">calc_RMSE</span>(pred, obs)
<span class="kw">return</span>(<span class="kw">list</span>(RMSE, fit, pred, obs, rtime))
}
}</code></pre></div>
</div>
<div id="RF_down" class="section level6">
<h6>7. RF DOWN</h6>
<blockquote>
<p><span class="math inline">\(Y\)</span> ~ logDEPTH, sst, inRCA, DAY, YEAR, LAT, LON</p>
</blockquote>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># RF DOWN downsamples the majority class (binomial component only)</span>
<span class="co"># downsample = if classes are imbalanced, train RF using equal #s of 0s and 1s</span>
fit_RF_DOWN <-<span class="st"> </span>function(dat, sp.ind, covar, fit.id, test.id){
btime <-<span class="st"> </span><span class="kw">Sys.time</span>()
<span class="co"># nmin <- sum(dat[fit.id, sp.ind])-1 # number of minority class (assume 1s)</span>
nmin <-<span class="st"> </span><span class="kw">table</span>(dat[fit.id,sp.ind])[<span class="dv">2</span>]; <span class="kw">names</span>(nmin) <-<span class="st"> </span><span class="ot">NULL</span>;
prop1 <-<span class="st"> </span>nmin/<span class="kw">length</span>(fit.id)
prop0 <-<span class="st"> </span><span class="dv">1</span>-prop1
if(prop0 <<span class="st"> </span>prop1) nmin <-<span class="st"> </span><span class="kw">length</span>(fit.id) -<span class="st"> </span>nmin <span class="co"># if 0s are minority, use # of 0s</span>
fit <-<span class="st"> </span><span class="kw">randomForest</span>(<span class="dt">sampsize=</span><span class="kw">rep</span>(<span class="kw">round</span>(nmin/<span class="dv">6</span>),<span class="dv">2</span>), <span class="dt">x=</span>dat[fit.id, covar],
<span class="dt">y=</span>dat[fit.id, sp.ind], <span class="dt">mtry=</span><span class="dv">3</span>, <span class="dt">ntree=</span><span class="dv">1000</span>,
<span class="dt">importance=</span><span class="ot">FALSE</span>, <span class="dt">do.trace=</span><span class="dv">250</span>, <span class="dt">keep.forest=</span><span class="ot">TRUE</span>)
<span class="co"># calculate and return performance</span>
etime <-<span class="st"> </span><span class="kw">Sys.time</span>()
rtime <-<span class="st"> </span>etime -<span class="st"> </span>btime
obs <-<span class="st"> </span>dat[test.id, sp.ind] <span class="co"># observations at test locations</span>
pred <-<span class="st"> </span><span class="kw">predict</span>(fit, <span class="dt">newdata=</span>dat[test.id,], <span class="dt">type=</span><span class="st">'prob'</span>)[,<span class="dv">2</span>]
AUC <-<span class="st"> </span><span class="kw">calc_AUC</span>(pred, obs)
<span class="kw">return</span>(<span class="kw">list</span>(AUC, fit, pred, obs, rtime))
}</code></pre></div>
</div>
<div id="RF_smote" class="section level6">
<h6>8. RF SMOTE</h6>
<blockquote>
<p><span class="math inline">\(Y\)</span> ~ logDEPTH, sst, inRCA, DAY, YEAR, LAT, LON</p>
</blockquote>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># RF SMOTE is also designed to improve RF for imbalanced data (binomial component only)</span>
<span class="co"># SMOTE = Synthetic Minority Over-sampling Technique</span>
<span class="co"># combines downsampling of majority class with oversampling of minority class</span>
<span class="co"># creates synthetic minority class instances by generating random linear combinations</span>
fit_RF_SMOTE <-<span class="st"> </span>function(dat, sp.ind, covar, fit.id, test.id){
btime <-<span class="st"> </span><span class="kw">Sys.time</span>()
prop <-<span class="st"> </span><span class="kw">table</span>(dat[fit.id, sp.ind])[<span class="dv">2</span>] /<span class="st"> </span><span class="kw">length</span>(fit.id) <span class="co"># get percent minority class (1s)</span>
p.over <-<span class="st"> </span><span class="kw">round</span>(<span class="dv">50</span>/prop) <span class="co"># percent to oversample to get to 50%</span>
p.under <-<span class="st"> </span><span class="kw">round</span>(<span class="dv">100</span>/(<span class="dv">1</span>-prop)) <span class="co"># percent to undersample to get to 50%</span>
X <-<span class="st"> </span><span class="kw">cbind</span>(dat[fit.id, covar], dat[fit.id, sp.ind])
<span class="kw">names</span>(X) <-<span class="st"> </span><span class="kw">c</span>(covar, <span class="st">"z"</span>)
formula.rf <-<span class="st"> </span><span class="kw">formula</span>(<span class="kw">paste0</span>(<span class="st">"z ~ "</span>, <span class="kw">paste0</span>(covar, <span class="dt">collapse=</span><span class="st">" + "</span>)))
X.SMOTE <-<span class="st"> </span><span class="kw">SMOTE</span>(formula.rf, <span class="dt">data=</span>X, <span class="dt">k=</span><span class="dv">5</span>, <span class="dt">perc.over=</span>p.over, <span class="dt">perc.under=</span>p.under)
<span class="co"># table(X.SMOTE$z) # check now we roughly have class balance</span>
fit <-<span class="st"> </span><span class="kw">randomForest</span>(<span class="dt">x=</span>X.SMOTE[,covar], <span class="dt">y=</span>X.SMOTE[,<span class="st">"z"</span>], <span class="dt">mtry=</span><span class="dv">3</span>, <span class="dt">ntree=</span><span class="dv">1000</span>, <span class="dt">importance=</span><span class="ot">FALSE</span>, <span class="dt">do.trace=</span><span class="dv">250</span>, <span class="dt">keep.forest=</span><span class="ot">TRUE</span>)
<span class="co"># calculate and return performance</span>
etime <-<span class="st"> </span><span class="kw">Sys.time</span>()
rtime <-<span class="st"> </span>etime -<span class="st"> </span>btime
obs <-<span class="st"> </span>dat[test.id, sp.ind] <span class="co"># observations at test locations</span>
<span class="co"># pred <- predict(fit, newdata=dat[test.id, covar], type='prob', predict.all=TRUE)</span>
pred <-<span class="st"> </span><span class="kw">predict</span>(fit, <span class="dt">newdata=</span>dat[test.id, covar], <span class="dt">type=</span><span class="st">'prob'</span>)[,<span class="dv">2</span>]
AUC <-<span class="st"> </span><span class="kw">calc_AUC</span>(pred, obs)
<span class="kw">return</span>(<span class="kw">list</span>(AUC, fit, pred, obs, rtime))
}</code></pre></div>
</div>
</div>
<div id="run-the-models" class="section level3">
<h3>Run the models</h3>
<p><strong>Warning: this took 40 hours on a 12-core 32gb RAM machine</strong></p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Set up binomial model storage</span>
species.bin <-<span class="st"> </span><span class="kw">c</span>(<span class="st">"DBRK"</span>,<span class="st">"PHLB"</span>,<span class="st">"YEYE"</span>)
n.species.bin <-<span class="st"> </span><span class="kw">length</span>(species.bin)
models.bin <-<span class="st"> </span><span class="kw">c</span>(<span class="st">"GLM"</span>,<span class="st">"GAM CONSTANT"</span>,<span class="st">"GAM IID"</span>,<span class="st">"GMRF CONSTANT"</span>,<span class="st">"GMRF EXCHANGEABLE"</span>,<span class="st">"RF BASE"</span>,<span class="st">"RF DOWN"</span>,<span class="st">"RF SMOTE"</span>)
n.models.bin <-<span class="st"> </span><span class="kw">length</span>(models.bin)
AUC <-<span class="st"> </span><span class="kw">array</span>(<span class="ot">NA</span>,<span class="dt">dim=</span><span class="kw">c</span>(n.species.bin, n.models.bin, k))
fits.bin <-<span class="st"> </span><span class="kw">vector</span>(<span class="st">"list"</span>, n.species.bin)
<span class="co"># Set up positive model storage</span>
species.pos <-<span class="st"> </span><span class="kw">c</span>(<span class="st">"DBRK"</span>,<span class="st">"PHLB"</span>)
n.species.pos <-<span class="st"> </span><span class="kw">length</span>(species.pos)
models.pos <-<span class="st"> </span><span class="kw">c</span>(<span class="st">"GLM"</span>,<span class="st">"GAM CONSTANT"</span>,<span class="st">"GAM IID"</span>,<span class="st">"GMRF CONSTANT"</span>,<span class="st">"GMRF EXCHANGEABLE"</span>,<span class="st">"RF BASE"</span>)
n.models.pos <-<span class="st"> </span><span class="kw">length</span>(models.pos)
RMSE <-<span class="st"> </span><span class="kw">array</span>(<span class="ot">NA</span>,<span class="dt">dim=</span><span class="kw">c</span>(n.species.pos, n.models.pos, k))
fits.pos <-<span class="st"> </span><span class="kw">vector</span>(<span class="st">"list"</span>, n.species.pos)
<span class="co"># Use same environmental covariates for all models</span>
covar <-<span class="st"> </span><span class="kw">c</span>(<span class="st">"logDEPTH"</span>, <span class="st">"logDEPTH2"</span>, <span class="st">"sst"</span>, <span class="st">"sst2"</span>, <span class="st">"inRCA"</span>, <span class="st">"DAY"</span>)
<span class="co"># Random forest includes lat/lon as covariates instead of spatial structures</span>
rf.covar <-<span class="st"> </span><span class="kw">c</span>(covar, <span class="st">"YEAR"</span>, <span class="st">"LAT"</span>, <span class="st">"LON"</span>)
<span class="co"># Run binomial models</span>
for(sp in <span class="dv">1</span>:n.species.bin){ <span class="co"># for each species</span>
modeltype <-<span class="st"> "binomial"</span>
sp.lab <-<span class="st"> </span>species.bin[sp]
sp.col <-<span class="st"> </span><span class="kw">paste0</span>(sp.lab,<span class="st">"_01"</span>)
sp.ind <-<span class="st"> </span><span class="kw">match</span>(sp.col, <span class="kw">names</span>(dat))
fits.bin[[sp]] <-<span class="st"> </span><span class="kw">vector</span>(<span class="st">"list"</span>, n.models.bin)
for(f in <span class="dv">1</span>:k){ <span class="co"># for each fold</span>
test.id <-<span class="st"> </span>ind[[sp]][[f]] <span class="co"># get test rows for this species and fold (10% of data)</span>
fit.id <-<span class="st"> </span>dat[-test.id,<span class="st">"id"</span>] <span class="co"># get rows to fit models (90% of data)</span>
<span class="co"># Fit GLM</span>
fits.bin[[sp]][[<span class="dv">1</span>]] <-<span class="st"> </span><span class="kw">fit_GLM</span>(dat, sp.ind, covar, modeltype, fit.id, test.id)
<span class="co"># Fit GAM CONSTANT</span>
fits.bin[[sp]][[<span class="dv">2</span>]] <-<span class="st"> </span><span class="kw">fit_GAM_CONSTANT</span>(dat, sp.ind, covar, modeltype, fit.id, test.id)
<span class="co"># Fit GAM IID</span>
fits.bin[[sp]][[<span class="dv">3</span>]] <-<span class="st"> </span><span class="kw">fit_GAM_IID</span>(dat, sp.ind, covar, modeltype, fit.id, test.id)
<span class="co"># Fit GMRF CONSTANT</span>
fits.bin[[sp]][[<span class="dv">4</span>]] <-<span class="st"> </span><span class="kw">fit_GMRF</span>(dat, sp.ind, covar, modeltype,
<span class="dt">modeltype.GMRF=</span><span class="st">"CONSTANT"</span>, fit.id, test.id)
<span class="co"># Fit GMRF EXCHANGEABLE</span>
fits.bin[[sp]][[<span class="dv">5</span>]] <-<span class="st"> </span><span class="kw">fit_GMRF</span>(dat, sp.ind, covar, modeltype,
<span class="dt">modeltype.GMRF=</span><span class="st">"EXCHANGEABLE"</span>, fit.id, test.id)
<span class="co"># Fit RF BASE</span>
fits.bin[[sp]][[<span class="dv">6</span>]] <-<span class="st"> </span><span class="kw">fit_RF_BASE</span>(dat, sp.ind, rf.covar, modeltype, fit.id, test.id)
<span class="co"># Fit RF DOWN</span>
fits.bin[[sp]][[<span class="dv">7</span>]] <-<span class="st"> </span><span class="kw">fit_RF_DOWN</span>(dat, sp.ind, rf.covar, fit.id, test.id)
<span class="co"># Fit RF SMOTE</span>
fits.bin[[sp]][[<span class="dv">8</span>]] <-<span class="st"> </span><span class="kw">fit_RF_SMOTE</span>(dat, sp.ind, rf.covar, fit.id, test.id)
}
}
<span class="co"># Run positive models</span>
for(sp in <span class="dv">1</span>:n.species.pos){ <span class="co"># for each species</span>
modeltype <-<span class="st"> "positive"</span>
sp.lab <-<span class="st"> </span>species.pos[sp]
sp.col <-<span class="st"> </span>sp.lab
sp.ind <-<span class="st"> </span><span class="kw">match</span>(sp.col, <span class="kw">names</span>(dat))
fits.pos[[sp]] <-<span class="st"> </span><span class="kw">vector</span>(<span class="st">"list"</span>, n.models.pos)
for(f in <span class="dv">1</span>:k){ <span class="co"># for each fold</span>
test.id <-<span class="st"> </span>ind[[sp]][[f]] <span class="co"># get test rows for this species and fold (10% of data)</span>
fit.id <-<span class="st"> </span>dat[-test.id,<span class="st">"id"</span>] <span class="co"># get rows to fit models (90% of data)</span>
<span class="co"># Only want to fit non-zero points in the positive model</span>
pos.fit <-<span class="st"> </span><span class="kw">which</span>(dat[fit.id, sp.ind] ><span class="st"> </span><span class="dv">0</span>)
fit.id <-<span class="st"> </span>fit.id[pos.fit]
pos.test <-<span class="st"> </span><span class="kw">which</span>(dat[test.id, sp.ind] ><span class="st"> </span><span class="dv">0</span>)
test.id <-<span class="st"> </span>test.id[pos.test]
<span class="co"># Fit GLM</span>
fits.pos[[sp]][[<span class="dv">1</span>]] <-<span class="st"> </span><span class="kw">fit_GLM</span>(dat, sp.ind, covar, modeltype, fit.id, test.id)
<span class="co"># Fit GAM CONSTANT</span>
fits.pos[[sp]][[<span class="dv">2</span>]] <-<span class="st"> </span><span class="kw">fit_GAM_CONSTANT</span>(dat, sp.ind, covar, modeltype, fit.id, test.id)
<span class="co"># GAM IID crashes for PHLB</span>
if(sp==<span class="dv">1</span>) fits.pos[[sp]][[f]][[<span class="dv">3</span>]] <-<span class="st"> </span><span class="kw">fit_GAM_IID</span>(dat, sp.ind, covar, modeltype, fit.id, test.id)
if(sp==<span class="dv">2</span>) fits.pos[[sp]][[f]][[<span class="dv">3</span>]] <-<span class="st"> </span><span class="ot">NULL</span>
<span class="co"># Fit GMRF CONSTANT</span>
fits.pos[[sp]][[<span class="dv">4</span>]] <-<span class="st"> </span><span class="kw">fit_GMRF</span>(dat, sp.ind, covar, modeltype,
<span class="dt">modeltype.GMRF=</span><span class="st">"CONSTANT"</span>, fit.id, test.id)
<span class="co"># Fit GMRF EXCHANGEABLE</span>
fits.pos[[sp]][[<span class="dv">5</span>]] <-<span class="st"> </span><span class="kw">fit_GMRF</span>(dat, sp.ind, covar, modeltype,
<span class="dt">modeltype.GMRF=</span><span class="st">"EXCHANGEABLE"</span>, fit.id, test.id)
<span class="co"># Fit RF BASE</span>
fits.pos[[sp]][[<span class="dv">6</span>]] <-<span class="st"> </span><span class="kw">fit_RF_BASE</span>(dat, sp.ind, rf.covar, modeltype, fit.id, test.id)
}
}</code></pre></div>
</div>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>