-
Notifications
You must be signed in to change notification settings - Fork 1
/
intro.html
1466 lines (1343 loc) · 65.3 KB
/
intro.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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>Machine learning for policy analysis</title>
<script src="site_libs/header-attrs-2.25/header-attrs.js"></script>
<script src="site_libs/jquery-3.6.0/jquery-3.6.0.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/flatly.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<style>h1 {font-size: 34px;}
h1.title {font-size: 38px;}
h2 {font-size: 30px;}
h3 {font-size: 24px;}
h4 {font-size: 18px;}
h5 {font-size: 16px;}
h6 {font-size: 12px;}
code {color: inherit; background-color: rgba(0, 0, 0, 0.04);}
pre:not([class]) { background-color: white }</style>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/highlightjs-9.12.0/default.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<link href="site_libs/vembedr-0.1.5/css/vembedr.css" rel="stylesheet" />
<link href="site_libs/font-awesome-6.4.2/css/all.min.css" rel="stylesheet" />
<link href="site_libs/font-awesome-6.4.2/css/v4-shims.min.css" rel="stylesheet" />
<style type="text/css">
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
</style>
<style type="text/css">code{white-space: pre;}</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
img {
max-width:100%;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
summary {
display: list-item;
}
details > summary > p:only-child {
display: inline;
}
pre code {
padding: 0;
}
</style>
<style type="text/css">
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #cccccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #adb5bd;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
border-radius: 6px 0 6px 6px;
}
</style>
<script type="text/javascript">
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark the anchor link active (and if it's in a dropdown, also mark that active)
var dropdown = menuAnchor.closest('li.dropdown');
if (window.bootstrap) { // Bootstrap 4+
menuAnchor.addClass('active');
dropdown.find('> .dropdown-toggle').addClass('active');
} else { // Bootstrap 3
menuAnchor.parent().addClass('active');
dropdown.addClass('active');
}
// Navbar adjustments
var navHeight = $(".navbar").first().height() + 15;
var style = document.createElement('style');
var pt = "padding-top: " + navHeight + "px; ";
var mt = "margin-top: -" + navHeight + "px; ";
var css = "";
// offset scroll position for anchor links (for fixed navbar)
for (var i = 1; i <= 6; i++) {
css += ".section h" + i + "{ " + pt + mt + "}\n";
}
style.innerHTML = "body {" + pt + "padding-bottom: 40px; }\n" + css;
document.head.appendChild(style);
});
</script>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs > li.active:before, .tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "\e259";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li.active:before {
content: "\e258";
font-family: 'Glyphicons Halflings';
border: none;
}
.tabset-dropdown > .nav-tabs > li.active {
display: block;
}
.tabset-dropdown > .nav-tabs > li > a,
.tabset-dropdown > .nav-tabs > li > a:focus,
.tabset-dropdown > .nav-tabs > li > a:hover {
border: none;
display: inline-block;
border-radius: 4px;
background-color: transparent;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li {
display: block;
float: none;
}
.tabset-dropdown > .nav-tabs > li {
display: none;
}
</style>
<!-- code folding -->
</head>
<body>
<div class="container-fluid main-container">
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-bs-toggle="collapse" data-target="#navbar" data-bs-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">Machine Learning for Public Policy</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="index.html">
<span class="fa fa-home"></span>
Home
</a>
</li>
<li>
<a href="intro.html">
<span class="fa fa-duotone fa-robot"></span>
Introduction
</a>
</li>
<li>
<a href="predictionpolicy.html">
<span class="fa fa-line-chart"></span>
Prediction Policy Problems
</a>
</li>
<li>
<a href="classification.html">
<span class="fa fa-solid fa-gears"></span>
Classification:Logistic
</a>
</li>
<li>
<a href="treebasedmodels.html">
<span class="fa fa-tree"></span>
TreeModels:RandomForests
</a>
</li>
<li>
<a href="fairml.html">
<span class="fa fa-graduation-cap"></span>
Fair ML/Data Ethics
</a>
</li>
<li>
<a href="NeuralNets.html">
<span class="fa fa-superpowers"></span>
Neural Networks
</a>
</li>
<li>
<a href="PolicyChallenge.html">
<span class="fa fa-thin fa-bolt-lightning"></span>
Policy Challenge
</a>
</li>
<li>
<a href="discussionboard.html">
<span class="fa fa-solid fa-comments"></span>
Discussion Board
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div id="header">
<h1 class="title toc-ignore">Machine learning for policy analysis</h1>
</div>
<style>
body {
text-align: justify}
</style>
<p>At its core, machine learning is primarily interested in making sense
of complex data. A machine learning algorithm’s job is to read data and
identify patterns that can be used for: prediction, feature-relevance
detection, model-free classification, among other actions.</p>
<p><span style="color: #7a3b2e;"><strong>Got any questions or thoughts
you want to share? Go to our <a
href="https://www.ml4pp-blog.com/">blog-style discussion board</a> and
leave a comment underneath the post dedicated to the introduction tab of
this site.</strong></span></p>
<p><br></p>
<p><strong>Please watch our Welcome video to meet the organisers and
hear from Alex Hunns about the dynamics of the course.In case you do not
make it until the end, here are some highlights:</strong></p>
<ul>
<li><p>It is a (mostly) self-paced and fully online course.</p></li>
<li><p>We provide a non-exhaustive way to go about using the R and
Python languages for basic Machine Learning purposes. Some of you may be
able to optimise a few lines of code, and we encourage that!</p></li>
<li><p>There are social hours in gather.town. Join so that you can meet
other Machine Learners around the globe!</p></li>
<li><p>There are no grades to this course. If you attend the
Collaborative Policy Event, you may be eligible for some form of
certification.</p></li>
<li><p>The content is introductory.</p></li>
<li><p>Be respectful and kind to other participants!</p></li>
</ul>
<p><br></p>
<center>
<div class="vembedr">
<div>
<iframe src="https://www.youtube.com/embed/sILhz3dqfqM" width="533" height="300" frameborder="0" allowfullscreen="" data-external="1"></iframe>
</div>
</div>
</center>
<div id="a-general-introduction"
class="section level2 tabset tabset-fade tabset-pills">
<h2 class="tabset tabset-fade tabset-pills"><strong>A general
introduction</strong></h2>
<div id="machine-learning-for-public-policy" class="section level3">
<h3><strong>Machine Learning for Public Policy</strong>:</h3>
<p>Empirical Public Policy research is primarily concerned with
causality and understanding counterfactuals. What is the impact of
Policy or Programme X on Population Outcome Y? What would have happened
in the absence of such a policy? However, there are policy problems that
may be solved without necessarily looking for a causal link. We call
these `prediction policy problems’ (<a
href="https://www.aeaweb.org/articles?id=10.1257/aer.p20151023">Kleinberg
et al. 2015</a>). Some examples include:</p>
<ul>
<li><p>Allocating fire and health inspectors in cities (<a
href="https://www.aeaweb.org/articles?id=10.1257/aer.p20161027">Glaeser
et al. 2016</a>).</p></li>
<li><p>Predicting unemployment spell length to help workers decide on
savings rates and job search strategies.</p></li>
<li><p>Predicting highest risk youth for targeting interventions (<a
href="https://www.aeaweb.org/articles?id=10.1257/aer.101.3.288">Chandler,Levitt,
and List 2011</a>).</p></li>
</ul>
<p><strong><em>How does a Machine Learn?</em></strong></p>
<p>Machine learning is classified in three major branches:</p>
<div
style="display: grid; grid-template-columns: 1fr 1fr 1fr; grid-column-gap: 8px">
<div>
<p><strong>Supervised Learning</strong>:</p>
<p>This course will be primarily concerned with supervised learning.
Supervised learning is analogous to statistical learning: suppose that
we observe a quantitative response <span
class="math inline">\(Y\)</span> and <span
class="math inline">\(p\)</span> predictors, <span
class="math inline">\(X_1, X_2,..., X_p\)</span>.</p>
<p>We can rewrite this in a general linear form as:</p>
<p><span class="math display">\[Y = f(X) + u\]</span> where <span
class="math inline">\(u\)</span> is an error term.</p>
</div>
<div>
<p><strong>Unsupervised Learning</strong>:</p>
<p>Unsupervised learning is known for reading data without labels; it is
more computationally complex than supervised learning (because it will
look for all possible patterns in the data), but it is also more
flexible than supervised learning. You can think of clustering, anomaly
detection, neural networks, etc.</p>
</div>
<div>
<p><strong>Reinforcement Learning</strong>:</p>
<p>Reinforcement learning is categorised as Artificial Intelligence. It
is more focused on goal-directed learning from interaction than are
other approaches to machine learning. As per <a
href="https://web.stanford.edu/class/psych209/Readings/SuttonBartoIPRLBook2ndEd.pdf">Sutton
and Barto (2015)</a>, the three most distinguishing features of
reinforcement learning are:</p>
<ol style="list-style-type: decimal">
<li><p>Being closed-loop; i.e. the learning system’s actions influence
its later inputs.</p></li>
<li><p>Does not have direct instructions as to what actions to take;
instead it must discover which actions yield the most reward by trying
them out.</p></li>
<li><p>Not knowing where the consequences of actions, including reward
signals, play out over extended time periods.</p></li>
</ol>
</div>
</div>
<center>
<div class="figure">
<img src="Images/sup_unsup_re.png" alt=" " width="65%" />
<p class="caption">
</p>
</div>
</center>
<p><strong>Relevant trade-offs in Machine Learning</strong></p>
<ul>
<li><p>Flexibility vs. interpretability: not all found patterns are
directly interpretable.</p></li>
<li><p>Prediction vs. inference: high predictive power does not allow
for proper inference.</p></li>
<li><p>Goodness-of-fit vs. over-fitting: how do we know <em>when</em>
the fit is good?</p></li>
</ul>
</div>
<div id="an-introduction-to-r-programming" class="section level3">
<h3><strong>An introduction to R programming</strong></h3>
<p>For the purposes of this course, we will be working with the
integrated development environment (IDE) Rstudio. Make sure you have <a
href="https://www.rstudio.com/products/rstudio/download/">downloaded
it</a> and have familiarised yourself with the interface before
proceeding.</p>
<p><strong>Features of R</strong></p>
<p>R is a statistical programming language. As such, it understands and
categorises its input as <strong>data types</strong>:</p>
<p><em>(Note that R is not too strict about data types, but you need to
be able to identify them to use them in math operations.)</em></p>
<p>Exammples of data types:</p>
<pre class="r"><code># Numeric (or double):
numeric_vector <- c(1, 1.0, 65.5)
print(numeric_vector)</code></pre>
<pre><code>## [1] 1.0 1.0 65.5</code></pre>
<pre class="r"><code>#Integers:
integer_vector <- c(1L, 3L, 45L)
print(integer_vector)</code></pre>
<pre><code>## [1] 1 3 45</code></pre>
<pre class="r"><code>#Logical (or boolean):
boolean_vector <- c(TRUE, FALSE)
print(boolean_vector)</code></pre>
<pre><code>## [1] TRUE FALSE</code></pre>
<pre class="r"><code>#Character:
character_vector <- c("Harry Potter", "Star Wars", "Lord of the Rings")
print(character_vector)</code></pre>
<pre><code>## [1] "Harry Potter" "Star Wars" "Lord of the Rings"</code></pre>
<pre class="r"><code>#Factor: (also knows as categorical variables)
factor_vector <- as.factor(c("male","female"))
print(factor_vector)</code></pre>
<pre><code>## [1] male female
## Levels: female male</code></pre>
<pre class="r"><code>#Missing:
NA</code></pre>
<pre><code>## [1] NA</code></pre>
<p>… and <strong>data structures</strong>. A data structure is either
homogeneous (all elements are of the same data type) or heterogeneous
(elements can be of more than one data type).</p>
<p>Examples of data structures:</p>
<p><em>Vectors</em>: think of a row, or a column of the same
element.</p>
<pre class="r"><code>#Vectors:
x <- c(1L,3L,5L,7L,9L) # we call this an integer vector
y <- c(1.3, 1, 5, 7, 11.2) # we call this a numerical (or double) vector
print(x)</code></pre>
<pre><code>## [1] 1 3 5 7 9</code></pre>
<pre class="r"><code>print(y)</code></pre>
<pre><code>## [1] 1.3 1.0 5.0 7.0 11.2</code></pre>
<p><em>Matrices</em>: they have rows and columns containing elements of
the same type.</p>
<pre class="r"><code>#Matrices:
A <- matrix(1:9, ncol=3, nrow=3, byrow= TRUE)
print(A)</code></pre>
<pre><code>## [,1] [,2] [,3]
## [1,] 1 2 3
## [2,] 4 5 6
## [3,] 7 8 9</code></pre>
<p><em>Arrays</em>: A vector is a one-dimensional array. A matrix is a
two-dimensional array. In short, an array is a collection of data of the
same type.</p>
<pre class="r"><code>#Arrays:
n <- 5*5*3
B <- array(1:n, c(5,5,3))
print(B)</code></pre>
<pre><code>## , , 1
##
## [,1] [,2] [,3] [,4] [,5]
## [1,] 1 6 11 16 21
## [2,] 2 7 12 17 22
## [3,] 3 8 13 18 23
## [4,] 4 9 14 19 24
## [5,] 5 10 15 20 25
##
## , , 2
##
## [,1] [,2] [,3] [,4] [,5]
## [1,] 26 31 36 41 46
## [2,] 27 32 37 42 47
## [3,] 28 33 38 43 48
## [4,] 29 34 39 44 49
## [5,] 30 35 40 45 50
##
## , , 3
##
## [,1] [,2] [,3] [,4] [,5]
## [1,] 51 56 61 66 71
## [2,] 52 57 62 67 72
## [3,] 53 58 63 68 73
## [4,] 54 59 64 69 74
## [5,] 55 60 65 70 75</code></pre>
<p><em>Lists</em>: a list is a one-dimensional, heterogeneous data
structure. Basically, it is an object that stores all object types.</p>
<pre class="r"><code>my_list <- list(42, "The answer is", TRUE)
print(my_list)</code></pre>
<pre><code>## [[1]]
## [1] 42
##
## [[2]]
## [1] "The answer is"
##
## [[3]]
## [1] TRUE</code></pre>
<p><em>Data frames</em>: a data frame is a list of column vectors. Each
vector must contain the same data type, but the different vectors can
store different data types. Note, however, that in a data frame all
vectors must have the same length.</p>
<pre class="r"><code>a <- 1L:5L
class(a)</code></pre>
<pre><code>## [1] "integer"</code></pre>
<pre class="r"><code>b <- c("a1", "b2", "c3", "d4", "e5")
class(b)</code></pre>
<pre><code>## [1] "character"</code></pre>
<pre class="r"><code>c <- c(TRUE, TRUE, FALSE, TRUE, FALSE)
class(c)</code></pre>
<pre><code>## [1] "logical"</code></pre>
<pre class="r"><code>df <- as.data.frame(cbind(a,b,c))
str(df)</code></pre>
<pre><code>## 'data.frame': 5 obs. of 3 variables:
## $ a: chr "1" "2" "3" "4" ...
## $ b: chr "a1" "b2" "c3" "d4" ...
## $ c: chr "TRUE" "TRUE" "FALSE" "TRUE" ...</code></pre>
<p>Notice that even though vector <em>a</em> in dataframe <em>df</em> is
of class integer, vector <em>b</em> is of class character, and vector
^<em>c</em> is of class boolean/logical, when binding them together they
have been coerced into factors. You’ll have to manually transform them
into their original class to be able to use them in math operations.</p>
<pre class="r"><code>df$a <- as.integer(df$a)
df$b <- as.character(df$b)
df$c <- as.logical(df$c)
str(df)</code></pre>
<pre><code>## 'data.frame': 5 obs. of 3 variables:
## $ a: int 1 2 3 4 5
## $ b: chr "a1" "b2" "c3" "d4" ...
## $ c: logi TRUE TRUE FALSE TRUE FALSE</code></pre>
<p>From here on, we will write an R script together, and learn some
basic commands and tools that will allow you to explore and manipulate
data. Please note that this is <strong>not</strong> an exhaustive
tutorial. It is nonetheless a good place to start.</p>
<p><strong>1. Setting up the Rstudio working environment</strong></p>
<p>It is good practice to make sure that the working environment is
empty/clean before you start running any code.</p>
<pre class="r"><code># The r base command rm() stands for remove
rm(list = ls()) # this line indicates R to clear absolutely everything from the environment</code></pre>
<p>Once that has been taken care of, you need to load the libraries you
will be working with. While r base has a large number of commands to
explore, wrangle, and manipulate data, the <strong>open source</strong>
feature of R means that people all over the world are constantly working
on packages and functions to make our lives easier. These can be used by
calling the libraries in which they are stored:</p>
<pre class="r"><code># My personal favourite are the Tidyverse library, by Hadley Whickam, and data.table. Both are brilliant for data exploration, manipulation, and visualisation.
library(tidyverse)
library(data.table)</code></pre>
<p>If you’re working with an imported data set, you should probably set
up your working directory as well:</p>
<pre class="r"><code>setwd("~/Desktop/") #Note that the squiggly symbol is a shortcut for Mac users, if you're a Windows user, please write the whole path.</code></pre>
<p>From the working directory, you can call documents: .csv files, .xls
and .xlsx, images, .txt, .dta (yes, STATA files!), and more. You’ll need
to use the right libraries to do so. For instance: <em>readxl</em> (from
the Tidyverse) uses the function <em>read_excel()</em> to import .xlsx
and .xls files. If you want to export a data frame in .xlsx format, you
can use the package <em>write_xlsx()</em>.</p>
<p><strong>2. R base commands for data set exploration</strong></p>
<p>Now that we have all the basic stuff set up, let’s start with some
basic r base commands that will allow us to explore our data. To do so,
we will work with the toy data set <em>mtcars</em> that can be called
from R without the need to upload data or call data from a website.</p>
<pre class="r"><code># some basics to explore your data
str(mtcars) # show the structure of the object in a compact format</code></pre>
<pre><code>## 'data.frame': 32 obs. of 11 variables:
## $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
## $ cyl : num 6 6 4 6 8 6 8 4 4 6 ...
## $ disp: num 160 160 108 258 360 ...
## $ hp : num 110 110 93 110 175 105 245 62 95 123 ...
## $ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
## $ wt : num 2.62 2.88 2.32 3.21 3.44 ...
## $ qsec: num 16.5 17 18.6 19.4 17 ...
## $ vs : num 0 0 1 1 0 1 0 1 1 1 ...
## $ am : num 1 1 1 0 0 0 0 0 0 0 ...
## $ gear: num 4 4 4 3 3 3 3 4 4 4 ...
## $ carb: num 4 4 1 1 2 1 4 2 2 4 ...</code></pre>
<pre class="r"><code>dim(mtcars) # inspect the dimension of the dataset (returns #rows, #columns)</code></pre>
<pre><code>## [1] 32 11</code></pre>
<pre class="r"><code>class(mtcars) # evaluate the class of the object (e.g. numeric, factor, character...)</code></pre>
<pre><code>## [1] "data.frame"</code></pre>
<pre class="r"><code>View(mtcars$mpg) # Try to avoid running this one in big and complex databases.
length(mtcars$mpg) # evaluate the number of elements in vector mpg</code></pre>
<pre><code>## [1] 32</code></pre>
<pre class="r"><code>mean(mtcars$mpg) # mean of all elements in vector mpg</code></pre>
<pre><code>## [1] 20.09062</code></pre>
<pre class="r"><code>sum(mtcars$mpg) # sum of all elements in vector mpg (similar to a column sum)</code></pre>
<pre><code>## [1] 642.9</code></pre>
<pre class="r"><code>sd(mtcars$mpg) # standard deviation</code></pre>
<pre><code>## [1] 6.026948</code></pre>
<pre class="r"><code>median(mtcars$mpg) # median</code></pre>
<pre><code>## [1] 19.2</code></pre>
<pre class="r"><code>cor(mtcars$mpg, mtcars$wt) # default is pearson correlation, specify method within function to change it. </code></pre>
<pre><code>## [1] -0.8676594</code></pre>
<pre class="r"><code>table(mtcars$am) #categorical data in a table: counts</code></pre>
<pre><code>##
## 0 1
## 19 13</code></pre>
<pre class="r"><code>prop.table(table(mtcars$am)) #categorical data in a table: proportions</code></pre>
<pre><code>##
## 0 1
## 0.59375 0.40625</code></pre>
<p><strong>3. Objects and assignments</strong></p>
<p>Another important feature of the R programming language is that it is
<em>object oriented</em>. For the most part, for every function used,
there must be an object assigned! Let’s see an example of object
assignment with a bivariate linear regression model:</p>
<pre class="r"><code>ols_model <- lm(mpg ~ wt, data = mtcars) # lm stands for linear model. In parenthesis, dependent variable first, independent variable after the squiggly.
summary(ols_model)</code></pre>
<pre><code>##
## Call:
## lm(formula = mpg ~ wt, data = mtcars)
##
## Residuals:
## Min 1Q Median 3Q Max
## -4.5432 -2.3647 -0.1252 1.4096 6.8727
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 37.2851 1.8776 19.858 < 2e-16 ***
## wt -5.3445 0.5591 -9.559 1.29e-10 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 3.046 on 30 degrees of freedom
## Multiple R-squared: 0.7528, Adjusted R-squared: 0.7446
## F-statistic: 91.38 on 1 and 30 DF, p-value: 1.294e-10</code></pre>
<p>If you would like to see the results from your regression, you do not
need to run it again. Instead, you print the object (ols_model) you have
assigned for the linear model function. Similarly, you can call
information stored in that object at any time, for example, the
estimated coefficients:</p>
<pre class="r"><code>ols_model$coefficients</code></pre>
<pre><code>## (Intercept) wt
## 37.285126 -5.344472</code></pre>
<p><em>If you want to read more about object oriented programming in R,
check out <a href="https://adv-r.hadley.nz/oo.html">Hadley Whickam’s
site</a></em></p>
<p><strong>4. Plotting with and without special libraries</strong></p>
<p>We had previously loaded a couple of libraries. Why did we do that if
we’ve only used r base commands so far? We’re going to exemplify the
power of libraries by drawing plots using r base, and ggplot2. Ggplot2
is the plotting function from the Tidyverse, and arguably one of the
best data visualisation tools across programming languages. If you’d
like to read more about why that is the case, check out the <a
href="https://ggplot2.tidyverse.org/">Grammar of Graphics</a> site.</p>
<p>Plotting with R base</p>
<pre class="r"><code>plot(mtcars$wt, mtcars$mpg, pch = 14, col = "grey", main ="Mileage and Weight")
abline(ols_model, col ="blue") # Note that to add a line of best fit, we had to call our previously estimate linear model, stored in the ols_model object-</code></pre>
<p><img src="intro_files/figure-html/unnamed-chunk-15-1.png" width="672" /></p>
<pre class="r"><code># with base R, you cannot directly assign an object to a plot, you need to use...
p_rbase <- recordPlot()
# plot.new() # don't forget to clean up your device afterwards!</code></pre>
<p>Plotting with ggplot2, using the grammar of graphics</p>
<pre class="r"><code># Steps in the Grammar of Graphics
# 1: linking plot to dataset,
# 2: defining (aes)thetic mapping,
# 3: use (geom)etric objects such as points, bars, etc. as markers,
# 4: the plot has layers
p_ggplot <- ggplot(data = mtcars, aes(x = wt, y = mpg, col=am )) + #the color is defined by car type (automatic 0 or manual 1)
geom_smooth(method = "lm", col= "orange") + # no need to run a regression ex-ante to add a line of best fit
geom_point(alpha=0.5) + #alpha controls transparency of the geom (a.k.a. data point)
theme(legend.position="none") #removing legend
print(p_ggplot)</code></pre>
<pre><code>## `geom_smooth()` using formula = 'y ~ x'</code></pre>
<p><img src="intro_files/figure-html/unnamed-chunk-16-1.png" width="672" /></p>
<p>Thanks to the grammar of graphics, we can continue to edit the plot
after we have finished it. Perhaps we’ve come up with ideas to make it
more stylish? Or helpful? Let’s see an example:</p>
<pre class="r"><code>p_ggplot <- p_ggplot + theme(legend.position = "right") # I am saving it with the same name again, but I could easily choose another name and keep two versions of the plot.
print(p_ggplot) # the legend we just added is NOT helpful. Why is that? </code></pre>
<pre><code>## `geom_smooth()` using formula = 'y ~ x'</code></pre>
<p><img src="intro_files/figure-html/unnamed-chunk-17-1.png" width="672" /></p>
<pre class="r"><code># Remember when we talked about data types?!
class(mtcars$am) #for legends, we might prefer levels/categories </code></pre>
<pre><code>## [1] "numeric"</code></pre>
<pre class="r"><code>mtcars$am <- as.factor(mtcars$am) # we have now transformed the numeric am into a factor variable
#the importance of assigning objects :)
# Now we can plot our scatterplot without issues
p_ggplot <- ggplot(data = mtcars, aes(x = wt, y = mpg, col = am )) +
geom_smooth(method = "lm", col= "red") +
geom_point(alpha=0.5) +
theme(legend.position="right") +
theme_classic()
print(p_ggplot)</code></pre>
<pre><code>## `geom_smooth()` using formula = 'y ~ x'</code></pre>
<p><img src="intro_files/figure-html/unnamed-chunk-17-2.png" width="672" /></p>
<pre class="r"><code># Shall we continue?
p_ggplot <- p_ggplot + ggtitle("Scatterplot of mileage vs weight of car") +
xlab("Weight of car") + ylab("Miles per gallon") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
p_ggplot <- p_ggplot + scale_colour_manual(name = "Automatic or Manual",
labels = c("0.Automatic", "1.Manual"),
values = c("darkorange2", "darkgoldenrod1"))
print(p_ggplot)</code></pre>
<pre><code>## `geom_smooth()` using formula = 'y ~ x'</code></pre>
<p><img src="intro_files/figure-html/unnamed-chunk-17-3.png" width="672" /></p>
<pre class="r"><code># Finally, perhaps we want two lines of best fit that follow the shape of the value dispersion by car type, and not the linear model function?
p <- ggplot(data = mtcars, aes(x = wt, y = mpg, col = am )) +
geom_smooth() +
geom_point(alpha=0.5) +
theme(legend.position="right") +
theme_classic() + ggtitle("Scatterplot of mileage vs weight of car") +
xlab("Weight of car") + ylab("Miles per gallon") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5)) +
scale_colour_manual(name = "Automatic or Manual",
labels = c("0.Automatic", "1.Manual"),
values = c("darkorange2", "darkgoldenrod1"))
print(p)</code></pre>
<pre><code>## `geom_smooth()` using method = 'loess' and formula =
## 'y ~ x'</code></pre>
<p><img src="intro_files/figure-html/unnamed-chunk-17-4.png" width="672" /></p>
<p><strong>5. R base capabilities and reserved names</strong></p>
<p>We’ve had some fun, now let’s go back to some r base basics. These
are going to be relevant for making algorithms of your own:</p>
<p><em>Arithmetic and other operations</em></p>
<pre class="r"><code>2+2 #addition</code></pre>
<pre><code>## [1] 4</code></pre>
<pre class="r"><code>5-2 #subtraction</code></pre>
<pre><code>## [1] 3</code></pre>
<pre class="r"><code>33.3/2 #division</code></pre>
<pre><code>## [1] 16.65</code></pre>
<pre class="r"><code>5^2 #exponentiation</code></pre>
<pre><code>## [1] 25</code></pre>
<pre class="r"><code>200 %/% 60 #integer division [or, how many full hours in 200 minutes?]/aka quotient</code></pre>
<pre><code>## [1] 3</code></pre>
<pre class="r"><code>200 %% 60 #remainder [or, how many minutes are left over? ]</code></pre>
<pre><code>## [1] 20</code></pre>
<p><em>Logical operators</em></p>
<pre class="r"><code>34 < 35 #smaller than</code></pre>
<pre><code>## [1] TRUE</code></pre>
<pre class="r"><code>34 < 35 | 33 #smaller than OR than (returns true if it is smaller than any one of them)</code></pre>
<pre><code>## [1] TRUE</code></pre>
<pre class="r"><code>34 > 35 & 33 #bigger than AND than (returns true only if both conditions apply)</code></pre>
<pre><code>## [1] FALSE</code></pre>
<pre class="r"><code>34 != 34 #negation</code></pre>
<pre><code>## [1] FALSE</code></pre>
<pre class="r"><code>34 %in% 1:100 #value matching (is the object contained in the list of items?)</code></pre>
<pre><code>## [1] TRUE</code></pre>
<pre class="r"><code>`%ni%` <- Negate(`%in%`) #let's create a function for NOT IN
1001 %ni% 1:100 # home-made function! :)</code></pre>
<pre><code>## [1] TRUE</code></pre>
<pre class="r"><code>34==34 #evaluation</code></pre>
<pre><code>## [1] TRUE</code></pre>
<p><em>Indexing</em></p>
<p>The tidyverse comes with a cool Starwars dataframe (or tibble, in the
tidyverse language). As long as you have loaded the tidyverse library,
you can use it.</p>
<pre class="r"><code>head(starwars) # print the first 5 elements of the dataframe/tibble</code></pre>
<pre><code>## # A tibble: 6 × 14
## name height mass hair_color skin_color eye_color birth_year sex gender
## <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr>
## 1 Luke Sky… 172 77 blond fair blue 19 male mascu…
## 2 C-3PO 167 75 <NA> gold yellow 112 none mascu…
## 3 R2-D2 96 32 <NA> white, bl… red 33 none mascu…
## 4 Darth Va… 202 136 none white yellow 41.9 male mascu…
## 5 Leia Org… 150 49 brown light brown 19 fema… femin…
## 6 Owen Lars 178 120 brown, gr… light blue 52 male mascu…
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## # vehicles <list>, starships <list></code></pre>
<pre class="r"><code>starwars$name[1] #indexing: extract the first element in the "name" vector from the starwars dataframe</code></pre>
<pre><code>## [1] "Luke Skywalker"</code></pre>
<pre class="r"><code>starwars[1,1] #alternative indexing: extract the element of row 1, col 1</code></pre>
<pre><code>## # A tibble: 1 × 1
## name
## <chr>
## 1 Luke Skywalker</code></pre>
<pre class="r"><code>starwars$name[2:4] # elements 2, 3, 4 of "name" vector</code></pre>
<pre><code>## [1] "C-3PO" "R2-D2" "Darth Vader"</code></pre>
<pre class="r"><code>starwars[,1] #extract all elements from column 1</code></pre>
<pre><code>## # A tibble: 87 × 1
## name
## <chr>
## 1 Luke Skywalker
## 2 C-3PO
## 3 R2-D2
## 4 Darth Vader
## 5 Leia Organa
## 6 Owen Lars
## 7 Beru Whitesun lars
## 8 R5-D4
## 9 Biggs Darklighter
## 10 Obi-Wan Kenobi
## # ℹ 77 more rows</code></pre>
<pre class="r"><code>starwars[1,] #extract all elements from row 1</code></pre>
<pre><code>## # A tibble: 1 × 14
## name height mass hair_color skin_color eye_color birth_year sex gender
## <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr>
## 1 Luke Sky… 172 77 blond fair blue 19 male mascu…
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## # vehicles <list>, starships <list></code></pre>
<pre class="r"><code>starwars$height[starwars$height<150] # returns a logical vector TRUE for elements >150 in height vector</code></pre>
<pre><code>## [1] 96 97 66 NA 88 137 112 94 122 79 96 NA NA NA NA NA</code></pre>
<pre class="r"><code>starwars[c('height', 'name')] #returns c(oncatenated) vectors</code></pre>
<pre><code>## # A tibble: 87 × 2
## height name
## <int> <chr>
## 1 172 Luke Skywalker
## 2 167 C-3PO
## 3 96 R2-D2
## 4 202 Darth Vader
## 5 150 Leia Organa
## 6 178 Owen Lars
## 7 165 Beru Whitesun lars
## 8 97 R5-D4
## 9 183 Biggs Darklighter
## 10 182 Obi-Wan Kenobi
## # ℹ 77 more rows</code></pre>
<p>We are now reaching the end of this brief introduction to R and
Rstudio. We will not go into the fun stuff you can do with data.table,
you can find that out on your own if you need to (but know it is a
powerful data wrangling package), and instead we will finalise with
<em>Reserved Names</em> in R. These are names you cannot use for your
objects, because they serve a programming purpose.</p>
<p><em>1. Not-observed data</em></p>
<pre class="r"><code># 1.1 NaN: results that cannot be reasonably defined
h <- 0/0
is.nan(h)</code></pre>
<pre><code>## [1] TRUE</code></pre>
<pre class="r"><code>class(h)</code></pre>
<pre><code>## [1] "numeric"</code></pre>
<pre class="r"><code>print(h)</code></pre>
<pre><code>## [1] NaN</code></pre>
<pre class="r"><code># 1.2 NA: missing data
colSums(is.na(starwars)) #How many missings in the starwars tibble*?</code></pre>
<pre><code>## name height mass hair_color skin_color eye_color birth_year
## 0 6 28 5 0 0 44
## sex gender homeworld species films vehicles starships
## 4 4 10 4 0 0 0</code></pre>
<pre class="r"><code>mean(starwars$height) # evaluation gives NA? Does that mean that the height vector is empty?!</code></pre>
<pre><code>## [1] NA</code></pre>
<pre class="r"><code>is.na(starwars$height) # logical vector returns 6 true statements for is.na (coincides with colSums table)</code></pre>
<pre><code>## [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [25] FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [37] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [49] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [61] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [73] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE
## [85] TRUE TRUE FALSE</code></pre>
<pre class="r"><code>class(starwars$height) # class evaluation returns integer...</code></pre>
<pre><code>## [1] "integer"</code></pre>
<pre class="r"><code>mean(as.integer(starwars$height), na.rm = TRUE) # read as integer, ignore NAs :) (rm stands for remove)</code></pre>
<pre><code>## [1] 174.358</code></pre>
<pre class="r"><code># missing values (NA) are regarded by R as non comparables, even to themselves, so if you ever encounter a missing values in a vector, make sure tto explicitly tell the function you are using what to do with them.</code></pre>
<p><em>2. if, else, ifelse, function, for, print, length (etc…)</em>
These words are reserved for control flow and looping.</p>
<pre class="r"><code># if else statements
meanheight <- 174.358
if ( meanheight < 175) {
print('very tall!')
} else {
print('average height')
} </code></pre>
<pre><code>## [1] "very tall!"</code></pre>
<pre class="r"><code># a note on using if else: else should be on the same line as if, otherwise it is not recognised
# home-made functions
f1 <- function(x){
return(sum(x+1))
}
print(f1(5)) # returns value of x+1 when x = 5</code></pre>
<pre><code>## [1] 6</code></pre>
<pre class="r"><code># for loops
class(starwars$height) # if it is not integer or numeric, then transform it! </code></pre>
<pre><code>## [1] "integer"</code></pre>
<pre class="r"><code>starwars$height <- as.numeric(as.character(starwars$height)) # transforming the height vector to numeric
starwars$height_judge = NA # if you're using a new object within a for loop, make sure you initialize it before running it
for (i in 1:length(starwars$height)) {
starwars$height_judge[i] <- ifelse(starwars$height[i]<100, "Short", "Tall")
}
print(starwars[c("name", "height_judge", "height")])</code></pre>
<pre><code>## # A tibble: 87 × 3
## name height_judge height
## <chr> <chr> <dbl>
## 1 Luke Skywalker Tall 172
## 2 C-3PO Tall 167
## 3 R2-D2 Short 96
## 4 Darth Vader Tall 202
## 5 Leia Organa Tall 150
## 6 Owen Lars Tall 178
## 7 Beru Whitesun lars Tall 165
## 8 R5-D4 Short 97
## 9 Biggs Darklighter Tall 183
## 10 Obi-Wan Kenobi Tall 182
## # ℹ 77 more rows</code></pre>
<p>You can download the R script by clicking on the button below.</p>
<a href="https://github.com/michelleg06/Machine-Learning-for-Public-Policy/blob/main/Gentle Intro to R and Rstudio.R">
<button class="btn btn-info"><i class="fa fa-save"></i> Download Intro to R script (.R)</button>
</a>
</div>
<div id="an-introduction-to-python-programming" class="section level3">
<h3><strong>An introduction to Python programming</strong></h3>
<p>If you would like to follow the course with Python, we will offer
some guidance. Bear in mind that the R and Python scripts are not meant
to be exact replicas of one another, this is because the languages offer
different data wrangling packages. However, you’ll be able to get to the
core of the course content.</p>
<p>With that said, let’s start with the first difference. Python does
not have a standard IDE like Rstudio for R. You can choose to work
directly with the console REPL, with Jupyter notebooks or the IDE Visual
Studio Code. We recommend to use VSCode, because it offers many
functionalities for code-sharing and collaboration, and you can
integrate AI-helpers to guide you throughout your coding tasks.</p>
<p><strong>Download VSCode and let’s get started! </strong></p>
<p>When you open the IDE VSCode, you’ll receive a prompt to start a new
project. Please make sure that when you do, you automatically save it in
a dedicated folder. This will be relevant for many reasons, but the most
pressing one is that you’ll want to create a Virtual Environment before
starting your script.</p>
<table>
<tbody>
<tr class="odd">
<td>A <strong>Python Virtual Environment</strong>, also referred to as
venv(s), is there to help us decouple and isolate package installs and
manage them, independently from pkgs that are provided by the system or
used by other projects. Although not strictly necessary, it is a good
practice that will save us a few headaches in the future.</td>
</tr>
</tbody>
</table>
<p>To create a virtual environment, once you’ve opened a new blank
project in VSC, click on shift + cmd + P (or F1) to open the Command
Palette (it should display from the top of VSC). Type “Python” and
select create python terminal. In the terminal, type `` python -m venv
venv ’’ and that’s it! You’ll notice the appearance of a venv folder in
your dedicated project folder.</p>
<p>Now, you’ll need to install and load the libraries you’ll need for
your project. To install them, use the python terminal you have opened.
It should be displayed in the bottom of the working environment. Use the
following (which should work with both Windows and Macbook, although Mac