-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLogistic.html
More file actions
2383 lines (2235 loc) · 170 KB
/
Logistic.html
File metadata and controls
2383 lines (2235 loc) · 170 KB
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 xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>
<meta charset="utf-8">
<meta name="generator" content="quarto-1.5.54">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<meta name="author" content="Dr. Martín Lozano.">
<title>Credit risk with R</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
div.columns{display: flex; gap: min(4vw, 1.5em);}
div.column{flex: auto; overflow-x: auto;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
ul.task-list li input[type="checkbox"] {
width: 0.8em;
margin: 0 0.8em 0.2em -1em; /* quarto-specific, see https://github.com/quarto-dev/quarto-cli/issues/4556 */
vertical-align: middle;
}
/* CSS for syntax highlighting */
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { display: inline-block; text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
}
pre.numberSource { margin-left: 3em; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
/* CSS for citations */
div.csl-bib-body { }
div.csl-entry {
clear: both;
margin-bottom: 0em;
}
.hanging-indent div.csl-entry {
margin-left:2em;
text-indent:-2em;
}
div.csl-left-margin {
min-width:2em;
float:left;
}
div.csl-right-inline {
margin-left:2em;
padding-left:1em;
}
div.csl-indent {
margin-left: 2em;
}</style>
<script src="Logistic_files/libs/clipboard/clipboard.min.js"></script>
<script src="Logistic_files/libs/quarto-html/quarto.js"></script>
<script src="Logistic_files/libs/quarto-html/popper.min.js"></script>
<script src="Logistic_files/libs/quarto-html/tippy.umd.min.js"></script>
<script src="Logistic_files/libs/quarto-html/anchor.min.js"></script>
<link href="Logistic_files/libs/quarto-html/tippy.css" rel="stylesheet">
<link href="Logistic_files/libs/quarto-html/quarto-syntax-highlighting.css" rel="stylesheet" class="quarto-color-scheme" id="quarto-text-highlighting-styles">
<link href="Logistic_files/libs/quarto-html/quarto-syntax-highlighting-dark.css" rel="prefetch" class="quarto-color-scheme quarto-color-alternate" id="quarto-text-highlighting-styles">
<script src="Logistic_files/libs/bootstrap/bootstrap.min.js"></script>
<link href="Logistic_files/libs/bootstrap/bootstrap-icons.css" rel="stylesheet">
<link href="Logistic_files/libs/bootstrap/bootstrap.min.css" rel="stylesheet" class="quarto-color-scheme" id="quarto-bootstrap" data-mode="light">
<link href="Logistic_files/libs/bootstrap/bootstrap-dark.min.css" rel="prefetch" class="quarto-color-scheme quarto-color-alternate" id="quarto-bootstrap" data-mode="dark">
<link href="Logistic_files/libs/quarto-contrib/fontawesome6-0.1.0/all.css" rel="stylesheet">
<link href="Logistic_files/libs/quarto-contrib/fontawesome6-0.1.0/latex-fontsize.css" rel="stylesheet">
<style>html{ scroll-behavior: smooth; }</style>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#btn-back-to-top {
position: fixed;
bottom: 20px;
right: 20px;
width: 15px; /* Adjust the width */
height: 15px; /* Adjust the height */
box-sizing: content-box;
z-index: 1000;
background-color: rgba(0, 123, 255, 0.7);
border: none;
color: white;
display: flex;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<button type="button" class="btn btn-primary btn-lg bi bi-arrow-up" id="btn-back-to-top"></button>
<script>
let backToTopButton = document.getElementById("btn-back-to-top");
backToTopButton.addEventListener("click", function () {
document.documentElement.scrollTop = 0;
});
</script>
<div id="progress-bar" style="width: 0%; height:2px; background-color: rgb(89 127 235);; position: fixed; top: 0px; z-index: 2000;"></div>
<script id="progressbar" type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
const bar = document.querySelector('#progress-bar');
const post = document.querySelector('#quarto-content');
const html = document.documentElement;
const height = post.scrollHeight + post.offsetTop;
window.addEventListener('scroll', () => {
bar.style.width = (html.scrollTop / (height- html.clientHeight)) * 100 + '%';
});
});
</script>
<link href="Logistic_files/libs/vembedr-0.1.5/css/vembedr.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/polyfill/v3/polyfill.min.js?features=es6"></script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml-full.js" type="text/javascript"></script>
<script type="text/javascript">
const typesetMath = (el) => {
if (window.MathJax) {
// MathJax Typeset
window.MathJax.typeset([el]);
} else if (window.katex) {
// KaTeX Render
var mathElements = el.getElementsByClassName("math");
var macros = [];
for (var i = 0; i < mathElements.length; i++) {
var texText = mathElements[i].firstChild;
if (mathElements[i].tagName == "SPAN") {
window.katex.render(texText.data, mathElements[i], {
displayMode: mathElements[i].classList.contains('display'),
throwOnError: false,
macros: macros,
fleqn: false
});
}
}
}
}
window.Quarto = {
typesetMath
};
</script>
<link rel="stylesheet" href="styles.css">
<div id="quarto-content" class="page-columns page-rows-contents page-layout-full toc-left">
<div id="quarto-sidebar-toc-left" class="sidebar toc-left">
<nav id="TOC" role="doc-toc" class="toc-active">
<h2 id="toc-title">Contents</h2>
<ul class="collapse">
<li><a href="#introduction." id="toc-introduction." class="nav-link active" data-scroll-target="#introduction.">Introduction.</a></li>
<li><a href="#loan-analysis." id="toc-loan-analysis." class="nav-link" data-scroll-target="#loan-analysis."><span class="header-section-number">1</span> Loan analysis.</a>
<ul class="collapse">
<li><a href="#explore-the-database." id="toc-explore-the-database." class="nav-link" data-scroll-target="#explore-the-database."><span class="header-section-number">1.1</span> Explore the database.</a></li>
<li><a href="#logistic-models." id="toc-logistic-models." class="nav-link" data-scroll-target="#logistic-models."><span class="header-section-number">1.2</span> Logistic models.</a></li>
<li><a href="#prediction-and-model-evaluation." id="toc-prediction-and-model-evaluation." class="nav-link" data-scroll-target="#prediction-and-model-evaluation."><span class="header-section-number">1.3</span> Prediction and model evaluation.</a></li>
<li><a href="#the-bank-strategy." id="toc-the-bank-strategy." class="nav-link" data-scroll-target="#the-bank-strategy."><span class="header-section-number">1.4</span> The bank strategy.</a></li>
</ul></li>
</ul>
</nav>
</div>
<div id="quarto-margin-sidebar" class="sidebar margin-sidebar zindex-bottom">
</div>
<main class="content column-page-right" id="quarto-document-content">
<header id="title-block-header" class="quarto-title-block default">
<div class="quarto-title">
<div class="quarto-title-block"><div><h1 class="title">Credit risk with <i class="fa-brands fa-r-project" aria-label="r-project"></i> <span style="color:white">R</span></h1><button type="button" class="btn code-tools-button dropdown-toggle" id="quarto-code-tools-menu" data-bs-toggle="dropdown" aria-expanded="false"><i class="bi"></i> Code</button><ul class="dropdown-menu dropdown-menu-end" aria-labelelledby="quarto-code-tools-menu"><li><a id="quarto-show-all-code" class="dropdown-item" href="javascript:void(0)" role="button">Show All Code</a></li><li><a id="quarto-hide-all-code" class="dropdown-item" href="javascript:void(0)" role="button">Hide All Code</a></li></ul></div></div>
</div>
<div class="quarto-title-meta column-page-right">
<div>
<div class="quarto-title-meta-heading">Author</div>
<div class="quarto-title-meta-contents">
<p>Dr. Martín Lozano. </p>
</div>
</div>
<div>
<div class="quarto-title-meta-heading">Modified</div>
<div class="quarto-title-meta-contents">
<p class="date-modified">December 25, 2024, 02:55:43 am.</p>
</div>
</div>
</div>
<div>
<div class="abstract">
<div class="block-title">Abstract</div>
This material relies on <span class="citation" data-cites="Hull">Hull (<a href="#ref-Hull" role="doc-biblioref">2015</a>)</span> credit risk chapters and Lore Dirick credit risk DataCamp course. Some mathematical background is skipped to emphasize the data analysis, model logic, discussion, graphical approach and R coding <span class="citation" data-cites="Rref">(<a href="#ref-Rref" role="doc-biblioref">R Core Team 2024</a>)</span>. As in the philosophy of <span class="citation" data-cites="knuth1984literate">Knuth (<a href="#ref-knuth1984literate" role="doc-biblioref">1984</a>)</span>, the objective of this document is to explain to human beings what we want a computer to do as literate programming. This is a work in progress and it is under revision.
</div>
</div>
</header>
<section id="introduction." class="level1 unnumbered">
<h1 class="unnumbered">Introduction.</h1>
<p>Credit risk models play a pivotal role in the financial landscape, providing institutions with a systematic framework to assess and manage the risks associated with lending and investment activities. One crucial component of these models is the estimation of the probability of default, which quantifies the likelihood that a borrower will fail to meet their debt obligations. The relevance of credit risk models lies in their ability to enhance decision-making processes by offering a comprehensive understanding of the potential creditworthiness of individuals, companies, or financial instruments. By utilizing statistical methods, historical data, and various financial indicators, these models enable financial institutions to make informed decisions about lending, pricing, and portfolio management. The estimation of the probability of default not only aids in risk assessment but also supports regulatory compliance, allowing institutions to maintain a healthy balance between risk and return in their credit portfolios. In an ever-evolving financial landscape, the continual refinement and application of credit risk models are essential for fostering stability and resilience within the financial system.</p>
</section>
<section id="loan-analysis." class="level1" data-number="1">
<h1 data-number="1"><span class="header-section-number">1</span> Loan analysis.</h1>
<p>The main objective of this section is to predict whether a person or client applying for a loan will repay it or not. This issue can be considered a classification problem, where based on information about the client and the characteristics of their loan application, the client is classified into one of two categories: whether they will default or not. There are various ways to approach this classification problem; in this section, we will use a simple machine learning model called logistic regression. The model is first estimated or trained and then evaluated using new data to determine how well it performs the classification.</p>
<p>Let’s load the required R packages first.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb1"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb1-1"><a href="#cb1-1"></a><span class="co"># Logistic models</span></span>
<span id="cb1-2"><a href="#cb1-2"></a><span class="fu">library</span>(gmodels) <span class="co"># CrossTable()</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stderr">
<pre><code>Warning: package 'gmodels' was built under R version 4.4.2</code></pre>
</div>
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb3"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb3-1"><a href="#cb3-1"></a><span class="fu">library</span>(ggplot2)</span>
<span id="cb3-2"><a href="#cb3-2"></a><span class="fu">library</span>(tidyr) <span class="co"># gather()</span></span>
<span id="cb3-3"><a href="#cb3-3"></a><span class="fu">library</span>(dplyr)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stderr">
<pre><code>
Adjuntando el paquete: 'dplyr'</code></pre>
</div>
<div class="cell-output cell-output-stderr">
<pre><code>The following objects are masked from 'package:stats':
filter, lag</code></pre>
</div>
<div class="cell-output cell-output-stderr">
<pre><code>The following objects are masked from 'package:base':
intersect, setdiff, setequal, union</code></pre>
</div>
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb7"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb7-1"><a href="#cb7-1"></a><span class="fu">library</span>(pROC) <span class="co"># roc</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stderr">
<pre><code>Warning: package 'pROC' was built under R version 4.4.2</code></pre>
</div>
<div class="cell-output cell-output-stderr">
<pre><code>Type 'citation("pROC")' for a citation.</code></pre>
</div>
<div class="cell-output cell-output-stderr">
<pre><code>
Adjuntando el paquete: 'pROC'</code></pre>
</div>
<div class="cell-output cell-output-stderr">
<pre><code>The following object is masked from 'package:gmodels':
ci</code></pre>
</div>
<div class="cell-output cell-output-stderr">
<pre><code>The following objects are masked from 'package:stats':
cov, smooth, var</code></pre>
</div>
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb13"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb13-1"><a href="#cb13-1"></a><span class="fu">library</span>(vembedr)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
</div>
<p>This section relies on the DataCamp course <em>Credit Risk Modeling in R</em> by Lore Dirick. However, we incorporate a slightly different database and an extended analysis.</p>
<section id="explore-the-database." class="level2" data-number="1.1">
<h2 data-number="1.1" class="anchored" data-anchor-id="explore-the-database."><span class="header-section-number">1.1</span> Explore the database.</h2>
<p>Let’s load the data called <tt><code>loan_data_ARF.rds</code></tt> and then understand its structure before conducting any further analysis. This database is available <a href="https://github.com/mlozanoqf/tutorial_arf/blob/main/loan_data_ARF.rds">here</a>.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb14"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb14-1"><a href="#cb14-1"></a>dat <span class="ot"><-</span> <span class="fu">readRDS</span>(<span class="st">"loan_data_ARF.rds"</span>)</span>
<span id="cb14-2"><a href="#cb14-2"></a><span class="fu">str</span>(dat)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>'data.frame': 29092 obs. of 10 variables:
$ loan_status : int 0 0 0 0 0 0 1 0 1 0 ...
$ loan_amnt : int 5000 2400 10000 5000 3000 12000 9000 3000 10000 1000 ...
$ int_rate : num 10.6 11 13.5 11 11 ...
$ grade : Factor w/ 7 levels "A","B","C","D",..: 2 3 3 1 5 2 3 2 2 4 ...
$ emp_length : int 10 25 13 3 9 11 0 3 3 0 ...
$ home_ownership: Factor w/ 4 levels "MORTGAGE","OTHER",..: 4 4 4 4 4 3 4 4 4 4 ...
$ annual_inc : num 24000 12252 49200 36000 48000 ...
$ age : int 33 31 24 39 24 28 22 22 28 22 ...
$ sex : Factor w/ 2 levels "0","1": 1 1 1 1 2 2 2 2 1 2 ...
$ region : Factor w/ 4 levels "E","N","S","W": 1 1 3 3 2 2 2 2 4 1 ...</code></pre>
</div>
</div>
<p>This dataset could represent a typical collection of data from a financial institution, such as a bank or a company that uses credit channels to sell its products or services. It contains 29,092 observations across 10 variables. Each observation corresponds to the personal and loan characteristics of an individual loan.</p>
<p>A key variable, our dependent variable, is <code>loan_st</code>, which indicates loan status. A value of 0 represents no default, while a value of 1 represents default. A default occurs when a borrower fails to make timely payments, misses payments, or ceases payments on the interest or principal owed. The definition of default can vary depending on the goals and interests of the analysis. For the purposes of this study, we classify loans simply as either default or no default.</p>
<p>The variable <code>loan_st</code> is dichotomous, or categorical. Our primary interest lies in predicting whether a new loan application will result in default or not.</p>
<p>Clearly, <code>loan_data_ARF.rds</code> represents past information, as we know with certainty whether an individual defaulted (1) or not (0). Historical data is valuable for understanding how likely an individual is to default based on their personal and loan characteristics. It is also essential for training quantitative models to predict outcomes for new applicants and for evaluating the performance of our classifications.</p>
<p>A variable name is considered too long when a shorter name can convey the same purpose just as effectively. Let’s rename some of them.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb16"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb16-1"><a href="#cb16-1"></a>old_names <span class="ot"><-</span> <span class="fu">colnames</span>(dat)</span>
<span id="cb16-2"><a href="#cb16-2"></a><span class="fu">colnames</span>(dat) <span class="ot"><-</span> <span class="fu">c</span>(<span class="st">"loan_st"</span>, <span class="st">"l_amnt"</span>, <span class="st">"int"</span>, <span class="st">"grade"</span>, <span class="st">"emp_len"</span>, </span>
<span id="cb16-3"><a href="#cb16-3"></a> <span class="st">"home"</span>, <span class="st">"income"</span>, <span class="st">"age"</span>, <span class="st">"sex"</span>, <span class="st">"region"</span>)</span>
<span id="cb16-4"><a href="#cb16-4"></a><span class="fu">data.frame</span>(old_names, <span class="st">"new_names"</span> <span class="ot">=</span> <span class="fu">colnames</span>(dat))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code> old_names new_names
1 loan_status loan_st
2 loan_amnt l_amnt
3 int_rate int
4 grade grade
5 emp_length emp_len
6 home_ownership home
7 annual_inc income
8 age age
9 sex sex
10 region region</code></pre>
</div>
</div>
<p>New variable names have now been assigned.</p>
<p>We can take a look at the information in different ways. For example, look at the first 10 rows out of 29,092.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb18"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb18-1"><a href="#cb18-1"></a><span class="fu">head</span>(dat, <span class="dv">10</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code> loan_st l_amnt int grade emp_len home income age sex region
1 0 5000 10.65 B 10 RENT 24000 33 0 E
2 0 2400 10.99 C 25 RENT 12252 31 0 E
3 0 10000 13.49 C 13 RENT 49200 24 0 S
4 0 5000 10.99 A 3 RENT 36000 39 0 S
5 0 3000 10.99 E 9 RENT 48000 24 1 N
6 0 12000 12.69 B 11 OWN 75000 28 1 N
7 1 9000 13.49 C 0 RENT 30000 22 1 N
8 0 3000 9.91 B 3 RENT 15000 22 1 N
9 1 10000 10.65 B 3 RENT 100000 28 0 W
10 0 1000 16.29 D 0 RENT 28000 22 1 E</code></pre>
</div>
</div>
<p>Note that <tt><code>sex</code></tt> is 1 for female and 0 for male. Now, instead of looking the details of the first 10 rows, we can summarize with respect to <tt><code>home</code></tt> with the <tt><code>CrossTable()</code></tt> function.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb20"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb20-1"><a href="#cb20-1"></a><span class="fu">CrossTable</span>(dat<span class="sc">$</span>home)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>
Cell Contents
|-------------------------|
| N |
| N / Table Total |
|-------------------------|
Total Observations in Table: 29092
| MORTGAGE | OTHER | OWN | RENT |
|-----------|-----------|-----------|-----------|
| 12002 | 97 | 2301 | 14692 |
| 0.413 | 0.003 | 0.079 | 0.505 |
|-----------|-----------|-----------|-----------|
</code></pre>
</div>
</div>
<p>We can also use <tt><code>CrossTable()</code></tt> to summarize two variables. In particular, instead of counting for home ownership we can add a second dimension like <tt><code>loan_st</code></tt>. This allows us to create more informative tables.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb22"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb22-1"><a href="#cb22-1"></a><span class="fu">CrossTable</span>(dat<span class="sc">$</span>home, dat<span class="sc">$</span>loan_st, <span class="at">prop.r =</span> <span class="cn">TRUE</span>,</span>
<span id="cb22-2"><a href="#cb22-2"></a> <span class="at">prop.c =</span> <span class="cn">FALSE</span>, <span class="at">prop.t =</span> <span class="cn">FALSE</span>, <span class="at">prop.chisq =</span> <span class="cn">FALSE</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>
Cell Contents
|-------------------------|
| N |
| N / Row Total |
|-------------------------|
Total Observations in Table: 29092
| dat$loan_st
dat$home | 0 | 1 | Row Total |
-------------|-----------|-----------|-----------|
MORTGAGE | 10821 | 1181 | 12002 |
| 0.902 | 0.098 | 0.413 |
-------------|-----------|-----------|-----------|
OTHER | 80 | 17 | 97 |
| 0.825 | 0.175 | 0.003 |
-------------|-----------|-----------|-----------|
OWN | 2049 | 252 | 2301 |
| 0.890 | 0.110 | 0.079 |
-------------|-----------|-----------|-----------|
RENT | 12915 | 1777 | 14692 |
| 0.879 | 0.121 | 0.505 |
-------------|-----------|-----------|-----------|
Column Total | 25865 | 3227 | 29092 |
-------------|-----------|-----------|-----------|
</code></pre>
</div>
</div>
<p>This table reveals defaults by home ownership. We can use histograms to see one variable distribution. In this case we have the interest rate distribution.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb24"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb24-1"><a href="#cb24-1"></a><span class="fu">ggplot</span>(dat, <span class="fu">aes</span>(<span class="at">x =</span> int)) <span class="sc">+</span> </span>
<span id="cb24-2"><a href="#cb24-2"></a> <span class="fu">geom_histogram</span>(<span class="fu">aes</span>(<span class="at">y=</span>..density..), <span class="at">binwidth =</span> <span class="fl">0.5</span>, <span class="at">colour =</span> <span class="st">"black"</span>, </span>
<span id="cb24-3"><a href="#cb24-3"></a> <span class="at">fill =</span> <span class="st">"white"</span>) <span class="sc">+</span></span>
<span id="cb24-4"><a href="#cb24-4"></a> <span class="fu">labs</span>(<span class="at">y =</span> <span class="st">"Density"</span>, <span class="at">x =</span> <span class="st">"Interest rate"</span>) <span class="sc">+</span></span>
<span id="cb24-5"><a href="#cb24-5"></a> <span class="fu">theme</span>(<span class="at">legend.position =</span> <span class="st">"bottom"</span>, <span class="at">legend.title =</span> <span class="fu">element_blank</span>())</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stderr">
<pre><code>Warning: The dot-dot notation (`..density..`) was deprecated in ggplot2 3.4.0.
ℹ Please use `after_stat(density)` instead.</code></pre>
</div>
<div class="cell-output-display">
<div id="fig-irh" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-irh-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="Logistic_files/figure-html/fig-irh-1.png" class="img-fluid figure-img" width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-irh-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 1.1: Interest rate histogram.
</figcaption>
</figure>
</div>
</div>
</div>
<p>The following is a dotplot figure for the annual income.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb26"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb26-1"><a href="#cb26-1"></a><span class="fu">ggplot</span>(dat, <span class="fu">aes</span>(income)) <span class="sc">+</span> </span>
<span id="cb26-2"><a href="#cb26-2"></a> <span class="fu">geom_dotplot</span>(<span class="at">binwidth =</span> <span class="dv">100000</span>, <span class="at">fill =</span> <span class="st">"blue"</span>) <span class="sc">+</span></span>
<span id="cb26-3"><a href="#cb26-3"></a> <span class="fu">labs</span>(<span class="at">y =</span> <span class="st">"Density"</span>,</span>
<span id="cb26-4"><a href="#cb26-4"></a> <span class="at">x =</span> <span class="st">"Annual income"</span>) <span class="sc">+</span></span>
<span id="cb26-5"><a href="#cb26-5"></a> <span class="fu">theme</span>(<span class="at">legend.position =</span> <span class="st">"bottom"</span>, <span class="at">legend.title =</span> <span class="fu">element_blank</span>())</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output-display">
<div id="fig-aib" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-aib-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="Logistic_files/figure-html/fig-aib-1.png" class="img-fluid figure-img" width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-aib-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 1.2: Annual income dotplot.
</figcaption>
</figure>
</div>
</div>
</div>
<p>The <a href="#fig-aib" class="quarto-xref">Figure 1.2</a> above appears suspicious. The horizontal axis shows a very large annual income value (6,000,000). Additionally, there are only a few individuals with extremely high incomes. We should investigate further to determine whether these are valid observations or errors in the original dataset.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb27"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb27-1"><a href="#cb27-1"></a>high_income <span class="ot"><-</span> dat[(dat<span class="sc">$</span>income <span class="sc">></span> <span class="dv">1000000</span>), ]</span>
<span id="cb27-2"><a href="#cb27-2"></a>high_income</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code> loan_st l_amnt int grade emp_len home income age sex region
4861 0 12025 14.27 C 13 RENT 1782000 63 0 E
13931 0 10000 6.54 A 16 OWN 1200000 36 0 W
15386 0 1500 10.99 A 5 MORTGAGE 1900000 60 1 N
16713 0 12000 7.51 A 1 MORTGAGE 1200000 32 0 E
19486 0 5000 12.73 C 12 MORTGAGE 6000000 144 1 E
22811 0 10000 10.99 A 1 MORTGAGE 1200000 40 1 E
23361 0 6400 7.40 A 7 MORTGAGE 1440000 44 1 E
23683 0 6600 7.74 A 9 MORTGAGE 1362000 47 0 E
28468 0 8450 12.29 C 0 RENT 2039784 42 0 E</code></pre>
</div>
</div>
<p>One individual (ID 19486) is not only extremely wealthy but also 144 years old. As a result, I have decided to remove these nine observations. Data cleaning is a common task when working with large datasets, and it is acceptable as long as the integrity of the data remains intact.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb29"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb29-1"><a href="#cb29-1"></a>high_income_index <span class="ot"><-</span> <span class="fu">data.frame</span>(<span class="at">value =</span> <span class="fu">as.integer</span>(<span class="fu">rownames</span>(high_income)))</span>
<span id="cb29-2"><a href="#cb29-2"></a>dat <span class="ot"><-</span> dat[<span class="sc">-</span>high_income_index<span class="sc">$</span>value,]</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
</div>
<p>Remember, the original dataset contains 29,092 rows. After removing 9 observations, we are left with 29,083 rows. Let’s take a look at the result.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb30"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb30-1"><a href="#cb30-1"></a><span class="fu">ggplot</span>(dat, <span class="fu">aes</span>(income)) <span class="sc">+</span> </span>
<span id="cb30-2"><a href="#cb30-2"></a> <span class="fu">geom_dotplot</span>(<span class="at">binwidth =</span> <span class="dv">10000</span>, <span class="at">fill =</span> <span class="st">"blue"</span>) <span class="sc">+</span></span>
<span id="cb30-3"><a href="#cb30-3"></a> <span class="fu">labs</span>(<span class="at">y =</span> <span class="st">"Density"</span>, <span class="at">x =</span> <span class="st">"Annual income"</span>) <span class="sc">+</span></span>
<span id="cb30-4"><a href="#cb30-4"></a> <span class="fu">theme</span>(<span class="at">legend.position =</span> <span class="st">"bottom"</span>, <span class="at">legend.title =</span> <span class="fu">element_blank</span>())</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output-display">
<div id="fig-aiwev" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-aiwev-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="Logistic_files/figure-html/fig-aiwev-1.png" class="img-fluid figure-img" width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-aiwev-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 1.3: Annual income without extreme values.
</figcaption>
</figure>
</div>
</div>
</div>
<p>Somewhat better now.</p>
<p>We could also explore some gender issues.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb31"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb31-1"><a href="#cb31-1"></a>summary_table <span class="ot"><-</span> dat <span class="sc">|></span></span>
<span id="cb31-2"><a href="#cb31-2"></a> <span class="fu">group_by</span>(sex) <span class="sc">|></span></span>
<span id="cb31-3"><a href="#cb31-3"></a> <span class="fu">summarize</span>(</span>
<span id="cb31-4"><a href="#cb31-4"></a> <span class="at">Mean =</span> <span class="fu">mean</span>(income),</span>
<span id="cb31-5"><a href="#cb31-5"></a> <span class="at">Median =</span> <span class="fu">median</span>(income),</span>
<span id="cb31-6"><a href="#cb31-6"></a> <span class="at">Min =</span> <span class="fu">min</span>(income),</span>
<span id="cb31-7"><a href="#cb31-7"></a> <span class="at">Max =</span> <span class="fu">max</span>(income),</span>
<span id="cb31-8"><a href="#cb31-8"></a> <span class="at">Count =</span> <span class="fu">n</span>()</span>
<span id="cb31-9"><a href="#cb31-9"></a> ) <span class="sc">|></span></span>
<span id="cb31-10"><a href="#cb31-10"></a> <span class="fu">mutate</span>(</span>
<span id="cb31-11"><a href="#cb31-11"></a> <span class="at">Gender =</span> <span class="fu">case_when</span>(</span>
<span id="cb31-12"><a href="#cb31-12"></a> sex <span class="sc">==</span> <span class="dv">0</span> <span class="sc">~</span> <span class="st">"Male"</span>,</span>
<span id="cb31-13"><a href="#cb31-13"></a> sex <span class="sc">==</span> <span class="dv">1</span> <span class="sc">~</span> <span class="st">"Female"</span></span>
<span id="cb31-14"><a href="#cb31-14"></a> )</span>
<span id="cb31-15"><a href="#cb31-15"></a> )</span>
<span id="cb31-16"><a href="#cb31-16"></a> </span>
<span id="cb31-17"><a href="#cb31-17"></a>summary_table</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code># A tibble: 2 × 7
sex Mean Median Min Max Count Gender
<fct> <dbl> <dbl> <dbl> <dbl> <int> <chr>
1 0 66021. 56000 4000 900000 13877 Male
2 1 67064. 57000 4200 948000 15206 Female</code></pre>
</div>
</div>
<p>The table shows that females tend to have slightly higher average and median incomes compared to males. Additionally, the income distribution for females appears more variable, with a wider range of incomes. While the sample sizes for both groups are similar, females are slightly more represented. Overall, the data suggests a modest income advantage for females and greater variability in their earnings.</p>
<p>The better we understand the data, the better positioned we are to analyze it, gain deeper insights into the problem, and interpret the solutions more effectively. However, there is a risk of falling into the trap of overexploration, losing sight of the main problem and failing to address the objectives. Data cleaning, for instance, can be an ongoing task. Removing outliers with excessively high incomes is just one example of how data cleaning can be approached. For now, we pause the exploration and cleaning process and move on to the next section, where we estimate models that will help us achieve the outlined objectives.</p>
</section>
<section id="logistic-models." class="level2" data-number="1.2">
<h2 data-number="1.2" class="anchored" data-anchor-id="logistic-models."><span class="header-section-number">1.2</span> Logistic models.</h2>
<p>Logistic models allows us to make predictions about loan defaults. Logistic regression is a statistical model that in its basic form uses a logistic function to model a binary dependent variable like <tt><code>loan_st</code></tt>. In this case, the binary dependent variable is default (1) or no default (0). A good reference for this section is <span class="citation" data-cites="hull2020machine">Hull (<a href="#ref-hull2020machine" role="doc-biblioref">2020</a>)</span>.</p>
<p>First, load the data and split it into two sets: (1) training and (2) test. The training set is for building and estimate models, and the test set is used to evaluate our model predictions with new data. When estimating models, it is common practice to separate the available data into two parts, <em>training</em> and <em>test</em> data, where the training data is used to estimate parameters (in-sample) and the test data is used to evaluate its accuracy (out of sample). Because the test data is not used in determining the estimation, it should provide a reliable indication of how well the model is likely to estimate or forecast on new data. In sum, we train the model, we test the model, and once we are OK with the model performance on new data, we are ready to use it in real-life applications. If we ignore this split and use the whole database to estimate our models, we may succeed at explaining defaults in our database but we may fail to explain defaults for new loan applications.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb33"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb33-1"><a href="#cb33-1"></a><span class="co"># It is convenient to set the loan status as factor.</span></span>
<span id="cb33-2"><a href="#cb33-2"></a>dat<span class="sc">$</span>loan_st <span class="ot"><-</span> <span class="fu">as.factor</span>(dat<span class="sc">$</span>loan_st)</span>
<span id="cb33-3"><a href="#cb33-3"></a><span class="fu">set.seed</span>(<span class="dv">567</span>)</span>
<span id="cb33-4"><a href="#cb33-4"></a>index_train <span class="ot"><-</span> <span class="fu">cbind</span>(<span class="fu">runif</span>(<span class="dv">1</span> <span class="sc">:</span> <span class="fu">nrow</span>(dat), <span class="dv">0</span> , <span class="dv">1</span>), <span class="fu">c</span>(<span class="dv">1</span> <span class="sc">:</span> <span class="fu">nrow</span>(dat)))</span>
<span id="cb33-5"><a href="#cb33-5"></a>index_train <span class="ot"><-</span> <span class="fu">order</span>(index_train[, <span class="dv">1</span>])</span>
<span id="cb33-6"><a href="#cb33-6"></a>index_train <span class="ot"><-</span> index_train[<span class="dv">1</span><span class="sc">:</span> (<span class="dv">2</span><span class="sc">/</span><span class="dv">3</span> <span class="sc">*</span> <span class="fu">nrow</span>(dat))]</span>
<span id="cb33-7"><a href="#cb33-7"></a><span class="co"># Create training set</span></span>
<span id="cb33-8"><a href="#cb33-8"></a>train <span class="ot"><-</span> dat[index_train, ]</span>
<span id="cb33-9"><a href="#cb33-9"></a><span class="co"># Create test set</span></span>
<span id="cb33-10"><a href="#cb33-10"></a>test <span class="ot"><-</span> dat[<span class="sc">-</span>index_train, ]</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
</div>
<p>Variables as factors are useful for model estimation and data visualization. Factors are variables in R which take on a limited number of different values; such variables are often referred to as categorical variables.</p>
<p>We have 29,083 observations in <tt><code>dat</code></tt>. The code above randomly selects <span class="math inline">\(29083 \times (2/3)=19388\)</span> rows to form the <tt><code>train</code></tt>. The <tt><code>test</code></tt> are the remaining <span class="math inline">\(29083-19388=9695\)</span> rows. The random selection is highly recommended as the <tt><code>dat</code></tt> may have some structure or sorting that could bias our model estimation and negatively impact our model test. For example, imagine that for some weird reason the database is sorted in such a way that the first observations are all no default. If that is the case, then the training and the test set would not have portions of default and no default cases and we may distort the whole analysis. The random selection allows us to replicate a real situation in which our database is unsorted, with different characteristics.</p>
<p>Let’s see if the recent created <tt><code>train</code></tt> and <tt><code>test</code></tt> have the same basic properties than <tt><code>dat</code></tt>.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb34"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb34-1"><a href="#cb34-1"></a><span class="co"># Combine data into a list for processing</span></span>
<span id="cb34-2"><a href="#cb34-2"></a>data_list <span class="ot"><-</span> <span class="fu">list</span>(<span class="at">dat =</span> dat<span class="sc">$</span>loan_st, <span class="at">train =</span> train<span class="sc">$</span>loan_st, <span class="at">test =</span> test<span class="sc">$</span>loan_st)</span>
<span id="cb34-3"><a href="#cb34-3"></a></span>
<span id="cb34-4"><a href="#cb34-4"></a><span class="co"># Compute proportions and combine into a data frame</span></span>
<span id="cb34-5"><a href="#cb34-5"></a>prop <span class="ot"><-</span> <span class="fu">do.call</span>(rbind, <span class="fu">lapply</span>(data_list, <span class="cf">function</span>(x) <span class="fu">prop.table</span>(<span class="fu">table</span>(x))))</span>
<span id="cb34-6"><a href="#cb34-6"></a><span class="fu">colnames</span>(prop) <span class="ot"><-</span> <span class="fu">c</span>(<span class="st">"no defaults"</span>, <span class="st">"defaults"</span>)</span>
<span id="cb34-7"><a href="#cb34-7"></a><span class="fu">row.names</span>(prop) <span class="ot"><-</span> <span class="fu">c</span>(<span class="st">"dat_prop"</span>, <span class="st">"train_prop"</span>, <span class="st">"test_prop"</span>)</span>
<span id="cb34-8"><a href="#cb34-8"></a>prop</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code> no defaults defaults
dat_prop 0.8890417 0.1109583
train_prop 0.8882298 0.1117702
test_prop 0.8906653 0.1093347</code></pre>
</div>
</div>
<p>The proportions of “defaults” and “no defaults” in the train and test datasets are very similar to those in the original dataset, indicating that both samples are representative. Specifically, the proportion of “defaults” in the train and test datasets closely matches that of the original dataset, as does the proportion of “no defaults.” This suggests that the random sampling process has preserved the overall distribution of the target variable, ensuring that the train and test sets reflect the characteristics of the full dataset.</p>
<p>Assume we think that the <tt><code>loan_st</code></tt> depends on the age of the individual. We can estimate a simple logistic model to learn about the relationship between age and loan status.</p>
<p><span class="math inline">\(\log\left(\frac{p}{1-p}\right) = \beta_0 + \beta_1 \times \text{age}\)</span>.</p>
<p>Where:</p>
<ul>
<li><p><span class="math inline">\(p\)</span> is the probability that <code>loan_st = 1</code> (e.g., the probability of default).</p></li>
<li><p><span class="math inline">\(\beta_0\)</span> is the intercept, and <span class="math inline">\(\beta_1\)</span> is the coefficient for the predictor variable <code>age</code>.</p></li>
</ul>
<p>The dependent variable in logistic regression is expressed as: <span class="math inline">\(\log\left(\frac{p}{1-p}\right)\)</span>. This transformation, known as the <em>logit function</em>, maps probabilities <span class="math inline">\(p\)</span> which range between 0 and 1 to the entire real number line <span class="math inline">\(-\infty\)</span> to <span class="math inline">\(+\infty\)</span>. This allows the model to establish a linear relationship between the independent variable(s) (e.g., age) and the transformed dependent variable, making estimation feasible. The fraction <span class="math inline">\(\frac{p}{1-p}\)</span>, called the <em>odds</em>, represents the ratio of the probability of an event happening <span class="math inline">\(p\)</span> to the probability of it not happening <span class="math inline">\(1-p\)</span>, making it a natural choice for modeling binary outcomes.</p>
<p>Let’s estimate the age model.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb36"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb36-1"><a href="#cb36-1"></a><span class="co"># Fitting a simple logistic model.</span></span>
<span id="cb36-2"><a href="#cb36-2"></a>logi_age <span class="ot"><-</span> <span class="fu">glm</span>(loan_st <span class="sc">~</span> age, <span class="at">family =</span> <span class="st">"binomial"</span>, <span class="at">data =</span> train)</span>
<span id="cb36-3"><a href="#cb36-3"></a>logi_age</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>
Call: glm(formula = loan_st ~ age, family = "binomial", data = train)
Coefficients:
(Intercept) age
-1.90097 -0.00623
Degrees of Freedom: 19387 Total (i.e. Null); 19386 Residual
Null Deviance: 13580
Residual Deviance: 13580 AIC: 13580</code></pre>
</div>
</div>
<p>The estimated model is: <span class="math inline">\(\log\left(\frac{p}{1-p}\right) = -1.90097 - 0.00623 \times \text{age}\)</span>.</p>
<p>The model suggests there is a negative relationship between age and loan status.</p>
<p>We can solve for <span class="math inline">\(p\)</span> to find the estimate of the probability of default according to the age model: <span class="math inline">\(p = \frac{\exp(-1.90097 - 0.00623 \times \text{age})}{1 + \exp(-1.90097 - 0.00623 \times \text{age})}\)</span>. Let’s evaluate <span class="math inline">\(p\)</span> for a couple of age values.</p>
<p>Substituting <code>age = 18</code>: <span class="math inline">\(p = \frac{\exp(-1.90097 - 0.00623 \times 18)}{1 + \exp(-1.90097 - 0.00623 \times 18)}\)</span>,</p>
<p><span class="math inline">\(p = \frac{\exp(-2.01311)}{1 + \exp(-2.01311)} \approx \frac{0.1333}{1 + 0.1333} \approx 0.1176\)</span>.</p>
<p>Substituting <code>age = 60</code>: <span class="math inline">\(p = \frac{\exp(-1.90097 - 0.00623 \times 60)}{1 + \exp(-1.90097 - 0.00623 \times 60)}\)</span>,</p>
<p><span class="math inline">\(p = \frac{\exp(-2.27477)}{1 + \exp(-2.27477)} \approx \frac{0.1037}{1 + 0.1037} \approx 0.0939\)</span>.</p>
<p>The results of the default probability estimation evaluated at ages 18 and 60 are not very promising because the difference in probabilities is very small. This means that the model does not generate significantly differentiated default probabilities, even when evaluated over a wide age range. This can be problematic because it suggests that this is a poor model.</p>
<p>The following is a graphical representation of the logistic regression model’s output.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb38"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb38-1"><a href="#cb38-1"></a><span class="co"># Define the function for the logistic regression model</span></span>
<span id="cb38-2"><a href="#cb38-2"></a>logistic_function <span class="ot"><-</span> <span class="cf">function</span>(age) {</span>
<span id="cb38-3"><a href="#cb38-3"></a> beta0 <span class="ot"><-</span> <span class="sc">-</span><span class="fl">1.90097</span></span>
<span id="cb38-4"><a href="#cb38-4"></a> beta1 <span class="ot"><-</span> <span class="sc">-</span><span class="fl">0.00623</span></span>
<span id="cb38-5"><a href="#cb38-5"></a> p <span class="ot"><-</span> <span class="fu">exp</span>(beta0 <span class="sc">+</span> beta1 <span class="sc">*</span> age) <span class="sc">/</span> (<span class="dv">1</span> <span class="sc">+</span> <span class="fu">exp</span>(beta0 <span class="sc">+</span> beta1 <span class="sc">*</span> age))</span>
<span id="cb38-6"><a href="#cb38-6"></a> <span class="fu">return</span>(p)</span>
<span id="cb38-7"><a href="#cb38-7"></a>}</span>
<span id="cb38-8"><a href="#cb38-8"></a></span>
<span id="cb38-9"><a href="#cb38-9"></a><span class="co"># Generate a sequence of ages</span></span>
<span id="cb38-10"><a href="#cb38-10"></a>ages <span class="ot"><-</span> <span class="fu">seq</span>(<span class="sc">-</span><span class="dv">1000</span>, <span class="dv">500</span>, <span class="at">by =</span> <span class="dv">1</span>)</span>
<span id="cb38-11"><a href="#cb38-11"></a></span>
<span id="cb38-12"><a href="#cb38-12"></a><span class="co"># Apply the logistic function to each age</span></span>
<span id="cb38-13"><a href="#cb38-13"></a>p_values <span class="ot"><-</span> <span class="fu">sapply</span>(ages, logistic_function)</span>
<span id="cb38-14"><a href="#cb38-14"></a></span>
<span id="cb38-15"><a href="#cb38-15"></a><span class="co"># Create the plot</span></span>
<span id="cb38-16"><a href="#cb38-16"></a><span class="fu">library</span>(ggplot2)</span>
<span id="cb38-17"><a href="#cb38-17"></a><span class="fu">ggplot</span>(<span class="at">data =</span> <span class="fu">data.frame</span>(<span class="at">age =</span> ages, <span class="at">p =</span> p_values), </span>
<span id="cb38-18"><a href="#cb38-18"></a> <span class="fu">aes</span>(<span class="at">x =</span> age, <span class="at">y =</span> p)) <span class="sc">+</span></span>
<span id="cb38-19"><a href="#cb38-19"></a> <span class="fu">geom_line</span>(<span class="at">color =</span> <span class="st">"blue"</span>, <span class="at">size =</span> <span class="dv">2</span>) <span class="sc">+</span></span>
<span id="cb38-20"><a href="#cb38-20"></a> <span class="fu">labs</span>(<span class="at">x =</span> <span class="st">"Age"</span>, <span class="at">y =</span> <span class="st">"Probability (p)"</span>) <span class="sc">+</span></span>
<span id="cb38-21"><a href="#cb38-21"></a> <span class="fu">theme_minimal</span>()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stderr">
<pre><code>Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
ℹ Please use `linewidth` instead.</code></pre>
</div>
<div class="cell-output-display">
<div id="fig-scolcam" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-scolcam-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="Logistic_files/figure-html/fig-scolcam-1.png" class="img-fluid figure-img" width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-scolcam-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 1.4: Sigmoid curve or logistic curve: age model.
</figcaption>
</figure>
</div>
</div>
</div>
<p>The logistic curve derived from this model is unreasonable because the probability <span class="math inline">\(p\)</span> changes very slowly with respect to age. This implies that, to observe the full range of probabilities from 0 to 1, we would require age values that are unrealistic or implausibly extreme. Such behavior suggests that the model is poorly specified, as it fails to generate meaningful distinctions in probabilities across a realistic range of ages.</p>
<p>The AIC value of the age model (13,580) is useful when comparing models. The Akaike information criterion (AIC) is a mathematical method for evaluating how well a model fits the data it was generated from. In statistics, AIC is used to compare different possible models and determine which one is the best fit for the data. At the moment we cannot interpret the AIC simply because we only have one model and we cannot compare it with another AIC.</p>
<p>Let’s estimate another simple model where the interest rate category is used as a predictor of the <tt><code>loan_st</code></tt>. Remember we are not conducting any prediction at all at this moment, we are only estimating models using the training set.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb40"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb40-1"><a href="#cb40-1"></a><span class="co"># Build a glm model with variable interest rate as a predictor.</span></span>
<span id="cb40-2"><a href="#cb40-2"></a>logi_int <span class="ot"><-</span> <span class="fu">glm</span>(<span class="at">formula =</span> loan_st <span class="sc">~</span> int, <span class="at">family =</span> <span class="st">"binomial"</span>, <span class="at">data =</span> train)</span>
<span id="cb40-3"><a href="#cb40-3"></a><span class="co"># Print the parameter estimates.</span></span>
<span id="cb40-4"><a href="#cb40-4"></a>logi_int</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>
Call: glm(formula = loan_st ~ int, family = "binomial", data = train)
Coefficients:
(Intercept) int
-3.710 0.142
Degrees of Freedom: 19387 Total (i.e. Null); 19386 Residual
Null Deviance: 13580
Residual Deviance: 13210 AIC: 13220</code></pre>
</div>
</div>
<p>The AIC is a lower (13,220 versus 13,580), so we have a better model now.</p>
<p>Using one single predictor as age or interest rate is clearly a limited approach. Let’s add some more predictors. Also, let’s introduce the <tt><code>summary()</code></tt> function to extract more information about the model estimation results. The <tt><code>logi_multi</code></tt> below assumes that the loan status depend on the age, interest rate, grade, loan amount, and annual income.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb42"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb42-1"><a href="#cb42-1"></a><span class="co"># Multiple variables in a logistic regression model.</span></span>
<span id="cb42-2"><a href="#cb42-2"></a>logi_multi <span class="ot"><-</span> <span class="fu">glm</span>(loan_st <span class="sc">~</span> age <span class="sc">+</span> int <span class="sc">+</span> grade <span class="sc">+</span> <span class="fu">log</span>(l_amnt) <span class="sc">+</span> </span>
<span id="cb42-3"><a href="#cb42-3"></a> <span class="fu">log</span>(income) , <span class="at">family =</span> <span class="st">"binomial"</span>, <span class="at">data =</span> train)</span>
<span id="cb42-4"><a href="#cb42-4"></a><span class="co"># Obtain significance levels using summary().</span></span>
<span id="cb42-5"><a href="#cb42-5"></a><span class="fu">summary</span>(logi_multi)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>
Call:
glm(formula = loan_st ~ age + int + grade + log(l_amnt) + log(income),
family = "binomial", data = train)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 1.996240 0.477911 4.177 2.95e-05 ***
age -0.002302 0.003825 -0.602 0.5473
int 0.038767 0.017249 2.247 0.0246 *
gradeB 0.503409 0.087435 5.758 8.54e-09 ***
gradeC 0.748229 0.117765 6.354 2.10e-10 ***
gradeD 0.964343 0.147283 6.548 5.85e-11 ***
gradeE 1.033442 0.190817 5.416 6.10e-08 ***
gradeF 1.619470 0.257900 6.279 3.40e-10 ***
gradeG 1.867494 0.440232 4.242 2.21e-05 ***
log(l_amnt) 0.015718 0.036341 0.433 0.6654
log(income) -0.470748 0.046423 -10.140 < 2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 13579 on 19387 degrees of freedom
Residual deviance: 13028 on 19377 degrees of freedom
AIC: 13050
Number of Fisher Scoring iterations: 5</code></pre>
</div>
</div>
<p>Our multi-factor model works well. In <tt><code>logi_multi</code></tt>, the AIC value is the lowest so far (13,050 versus 13,220), so this should be considered as the best in-sample model at the moment. The <tt><code>summary()</code></tt> function shows the significance levels of the estimators, but we are currently more interested in the goodness of fit of the models because we want to conduct predictions about the <tt><code>loan_st</code></tt>. This is, we are interested to use a model to find out whether new applicants in the test set are expected to default or not, rather than in the applicants’ credit risk factors. This is why we are concentrated in AIC now.</p>
<p>When a customer fill out a credit application form, we collect information but we do not know for sure whether she or he will eventually default. A credit risk model can help us in this task.</p>
</section>
<section id="prediction-and-model-evaluation." class="level2" data-number="1.3">
<h2 data-number="1.3" class="anchored" data-anchor-id="prediction-and-model-evaluation."><span class="header-section-number">1.3</span> Prediction and model evaluation.</h2>
<p>Let’s take our three models: <tt><code>logi_age</code></tt>, <tt><code>logi_int</code></tt> and <tt><code>logi_multi</code></tt> from the previous subsection to carry out a simple prediction exercise. We start by identifying one observation in the test set and ask the models to predict the <tt><code>loan_st</code></tt>. This is, we take the first guy age, then we apply the <tt><code>logi_age</code></tt> model, and compare the predicted <tt><code>loan_st</code></tt> with respect to what really happened. Remember we know what really happened with this guy because we have the information in the test set. Every model is expected to produce different <tt><code>loan_st</code></tt> predictions. If the model is good, then the predicted <tt><code>loan_st</code></tt> will match what really happened.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb44"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb44-1"><a href="#cb44-1"></a><span class="co"># Define one single observation in test_set.</span></span>
<span id="cb44-2"><a href="#cb44-2"></a>John_Doe <span class="ot"><-</span> <span class="fu">as.data.frame</span>(test[<span class="dv">1</span>, ])</span>
<span id="cb44-3"><a href="#cb44-3"></a>John_Doe</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code> loan_st l_amnt int grade emp_len home income age sex region
1 0 5000 10.65 B 10 RENT 24000 33 0 E</code></pre>
</div>
</div>
<p>We know in advance that the <tt><code>loan_st</code></tt> of this observation taken from the test set is 0. However, the models cannot know this simply because we did not use the test set to estimate the logistic models. Our models were estimated using the training set. A good credit risk model should predict a no default given this new applicant.</p>
<p>The values of <tt><code>loan_st</code></tt> in the test set is either 0 or 1. However, the logistic models estimate the <tt><code>loan_st</code></tt> as values in the range of 0 to 1. This mean that we would expect the estimated <tt><code>loan_st</code></tt> to be close to 0. <em>But, how close?</em> We will deal with this issue later.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb46"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb46-1"><a href="#cb46-1"></a><span class="co"># Predict the loan status.</span></span>
<span id="cb46-2"><a href="#cb46-2"></a>logi_age_pred <span class="ot"><-</span> <span class="fu">predict</span>(logi_age, <span class="at">newdata =</span> John_Doe, <span class="at">type =</span> <span class="st">"response"</span>)</span>
<span id="cb46-3"><a href="#cb46-3"></a>logi_int_pred <span class="ot"><-</span> <span class="fu">predict</span>(logi_int, <span class="at">newdata =</span> John_Doe, <span class="at">type =</span> <span class="st">"response"</span>)</span>
<span id="cb46-4"><a href="#cb46-4"></a>logi_multi_pred <span class="ot"><-</span> <span class="fu">predict</span>(logi_multi, <span class="at">newdata =</span> John_Doe, <span class="at">type =</span> <span class="st">"response"</span>)</span>
<span id="cb46-5"><a href="#cb46-5"></a><span class="co"># Collect all.</span></span>
<span id="cb46-6"><a href="#cb46-6"></a>pred_John <span class="ot"><-</span> <span class="fu">rbind</span>(<span class="st">"logi_age"</span> <span class="ot">=</span> logi_age_pred, </span>
<span id="cb46-7"><a href="#cb46-7"></a> <span class="st">"logi_int"</span> <span class="ot">=</span> logi_int_pred, </span>
<span id="cb46-8"><a href="#cb46-8"></a> <span class="st">"logi_multi"</span> <span class="ot">=</span> logi_multi_pred)</span>
<span id="cb46-9"><a href="#cb46-9"></a><span class="co"># Prepare a table.</span></span>
<span id="cb46-10"><a href="#cb46-10"></a><span class="fu">colnames</span>(pred_John) <span class="ot"><-</span> <span class="st">"Loan status predictions for John Doe."</span></span>
<span id="cb46-11"><a href="#cb46-11"></a>pred_John</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code> Loan status predictions for John Doe.
logi_age 0.10846236
logi_int 0.09996702
logi_multi 0.14461840</code></pre>
</div>
</div>
<p>These values are low as they are close to 0. We could interpret this as a certain ability of the models to predict this single case from the test set. However, several questions remains unanswered and requires further analysis. For example: <em>How can we determine if the prediction is low enough to consider it as a non-default?</em> We may need a cut-off value to decide. We will explore this issue later.</p>
<p>Another aspect is: <em>What about the rest of the cases in the test set?</em> We have 9,695 observations in the test set and in the example above we only test for the first one. We are interested in the entire test set, not only for John Doe. Fortunately, this issue is easy to address as we only need to change the <tt><code>newdata</code></tt> parameter in the <tt><code>predict()</code></tt> function. In particular, instead of <tt><code>newdata = John_Doe</code></tt>, which is one observation, and can change it to <tt><code>newdata = test</code></tt>, which is the entire 9,695 test set.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb48"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb48-1"><a href="#cb48-1"></a><span class="co"># Predict the loan status with the three models.</span></span>
<span id="cb48-2"><a href="#cb48-2"></a>pred_logi_age <span class="ot"><-</span> <span class="fu">predict</span>(logi_age, <span class="at">newdata =</span> test, <span class="at">type =</span> <span class="st">"response"</span>)</span>
<span id="cb48-3"><a href="#cb48-3"></a>pred_logi_int <span class="ot"><-</span> <span class="fu">predict</span>(logi_int, <span class="at">newdata =</span> test, <span class="at">type =</span> <span class="st">"response"</span>)</span>
<span id="cb48-4"><a href="#cb48-4"></a>pred_logi_multi <span class="ot"><-</span> <span class="fu">predict</span>(logi_multi, <span class="at">newdata =</span> test, </span>
<span id="cb48-5"><a href="#cb48-5"></a> <span class="at">type =</span> <span class="st">"response"</span>)</span>
<span id="cb48-6"><a href="#cb48-6"></a></span>
<span id="cb48-7"><a href="#cb48-7"></a>pred_range <span class="ot"><-</span> <span class="fu">rbind</span>(<span class="st">"logi_age"</span> <span class="ot">=</span> <span class="fu">range</span>(pred_logi_age), </span>
<span id="cb48-8"><a href="#cb48-8"></a> <span class="st">"logi_int"</span> <span class="ot">=</span> <span class="fu">range</span>(pred_logi_int),</span>
<span id="cb48-9"><a href="#cb48-9"></a> <span class="st">"logi_multi"</span> <span class="ot">=</span> <span class="fu">range</span>(pred_logi_multi))</span>
<span id="cb48-10"><a href="#cb48-10"></a>aic <span class="ot"><-</span> <span class="fu">rbind</span>(logi_age<span class="sc">$</span>aic, logi_int<span class="sc">$</span>aic, logi_multi<span class="sc">$</span>aic)</span>
<span id="cb48-11"><a href="#cb48-11"></a>pred_range <span class="ot"><-</span> <span class="fu">cbind</span>(pred_range, aic)</span>
<span id="cb48-12"><a href="#cb48-12"></a><span class="fu">colnames</span>(pred_range) <span class="ot"><-</span> <span class="fu">c</span>(<span class="st">"min(loan_st)"</span>, <span class="st">"max(loan_st)"</span>, <span class="st">"AIC"</span>)</span>
<span id="cb48-13"><a href="#cb48-13"></a>pred_range</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code> min(loan_st) max(loan_st) AIC
logi_age 0.08417892 0.1165453 13580.65
logi_int 0.05019756 0.3982977 13215.61
logi_multi 0.01739107 0.4668004 13050.30</code></pre>
</div>
</div>
<p>Now, instead of the prediction of one single applicant we have conducted a prediction of all 9,695 applicants in the test set. The lower value column corresponds to the lower predicted <tt><code>loan_st</code></tt> for each model. The logistic models produce values in the range of zero to one, and in this case the ranges are rather narrow.</p>
<p>Narrow ranges (the difference between higher and lower <tt><code>loan_st</code></tt> predicted values) could be problematic because the model could not be able to discriminate between defaults (predictions closer to 1) and no-defaults (predictions closer to 0). The higher AIC corresponds to the worst in-sample model and the lower AIC to the best in-sample model. Here, we can see some in and out of sample consistency because the best model according to the AIC, corresponds to the model with the higher prediction range.</p>
<p>Let’s explore all the predicted <tt><code>loan_st</code></tt> values for the <tt><code>logi_age</code></tt>:</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb50"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb50-1"><a href="#cb50-1"></a><span class="fu">ggplot</span>(<span class="fu">data.frame</span>(pred_logi_age), <span class="fu">aes</span>(<span class="at">x =</span> pred_logi_age)) <span class="sc">+</span> </span>
<span id="cb50-2"><a href="#cb50-2"></a> <span class="fu">geom_density</span>(<span class="at">fill =</span> <span class="st">"red"</span>) <span class="sc">+</span></span>
<span id="cb50-3"><a href="#cb50-3"></a> <span class="fu">labs</span>(<span class="at">y =</span> <span class="st">"Density"</span>, <span class="at">x =</span> <span class="st">"Default prediction"</span>) <span class="sc">+</span></span>
<span id="cb50-4"><a href="#cb50-4"></a> <span class="fu">theme</span>(<span class="at">legend.position =</span> <span class="st">"bottom"</span>, <span class="at">legend.title =</span> <span class="fu">element_blank</span>())</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output-display">
<div id="fig-amph" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-amph-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="Logistic_files/figure-html/fig-amph-1.png" class="img-fluid figure-img" width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-amph-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 1.5: Age model prediction histogram.
</figcaption>
</figure>
</div>
</div>
</div>
<p>The <tt><code>logi_age</code></tt> fails to predict values ranging from 0 to 1. In fact, these values are quite concentrated in a very small range of values. As a consequence, this model fails to differentiate between default and no default predictions.</p>
<p>Let’s visualize the predictions of the <tt><code>logi_int</code></tt> and <tt><code>logi_multi</code></tt>. We first collect all predictions in a single data frame just for convenience.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb51"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb51-1"><a href="#cb51-1"></a>pred_logi <span class="ot"><-</span> <span class="fu">data.frame</span>(<span class="fu">cbind</span>(pred_logi_age, pred_logi_int,</span>
<span id="cb51-2"><a href="#cb51-2"></a> pred_logi_multi))</span>
<span id="cb51-3"><a href="#cb51-3"></a>pred_logi <span class="ot"><-</span> <span class="fu">gather</span>(pred_logi, <span class="at">key =</span> <span class="st">"model"</span>, <span class="at">value =</span> <span class="st">"pred"</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
</div>
<p>Now we plot the <tt><code>logi_int</code></tt> and <tt><code>logi_multi</code></tt>.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb52"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb52-1"><a href="#cb52-1"></a><span class="fu">ggplot</span>(pred_logi[pred_logi<span class="sc">$</span>model <span class="sc">!=</span> <span class="st">"pred_logi_age"</span>,], </span>
<span id="cb52-2"><a href="#cb52-2"></a> <span class="fu">aes</span>(<span class="at">x =</span> pred, <span class="at">fill =</span> model)) <span class="sc">+</span> </span>
<span id="cb52-3"><a href="#cb52-3"></a> <span class="fu">geom_density</span>(<span class="at">alpha =</span> <span class="fl">0.4</span>) <span class="sc">+</span></span>
<span id="cb52-4"><a href="#cb52-4"></a> <span class="fu">labs</span>(<span class="at">y =</span> <span class="st">"Density"</span>, <span class="at">x =</span> <span class="st">"Default prediction"</span>) <span class="sc">+</span></span>
<span id="cb52-5"><a href="#cb52-5"></a> <span class="fu">theme</span>(<span class="at">legend.position =</span> <span class="st">"bottom"</span>, <span class="at">legend.title =</span> <span class="fu">element_blank</span>())</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output-display">
<div id="fig-irammph" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-irammph-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="Logistic_files/figure-html/fig-irammph-1.png" class="img-fluid figure-img" width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-irammph-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 1.6: Interest rate and multi models predictions histograms.
</figcaption>
</figure>
</div>
</div>
</div>
<p>Let’s add the <tt><code>age</code></tt> model as well.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb53"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb53-1"><a href="#cb53-1"></a><span class="fu">ggplot</span>(pred_logi, <span class="fu">aes</span>(<span class="at">x =</span> pred, <span class="at">y =</span> model, <span class="at">fill =</span> model)) <span class="sc">+</span> </span>
<span id="cb53-2"><a href="#cb53-2"></a> <span class="fu">geom_boxplot</span>() <span class="sc">+</span></span>
<span id="cb53-3"><a href="#cb53-3"></a> <span class="fu">labs</span>(<span class="at">y =</span> <span class="st">"Model"</span>, <span class="at">x =</span> <span class="st">"Default prediction"</span>) <span class="sc">+</span></span>
<span id="cb53-4"><a href="#cb53-4"></a> <span class="fu">theme</span>(<span class="at">legend.position =</span> <span class="st">"none"</span>, <span class="at">legend.title =</span> <span class="fu">element_blank</span>())</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output-display">
<div id="fig-aairaammpb" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-aairaammpb-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="Logistic_files/figure-html/fig-aairaammpb-1.png" class="img-fluid figure-img" width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-aairaammpb-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 1.7: Age, Interest rate and multi models predictions boxplot.
</figcaption>
</figure>
</div>
</div>
</div>
<p>Presumably, a model which considers all available predictors could be better for predicting the <tt><code>loan_st</code></tt>.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb54"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb54-1"><a href="#cb54-1"></a><span class="co"># Logistic regression model using all available predictors in the data set.</span></span>
<span id="cb54-2"><a href="#cb54-2"></a>logi_full <span class="ot"><-</span> <span class="fu">glm</span>(loan_st <span class="sc">~</span> age <span class="sc">+</span> int <span class="sc">+</span> grade <span class="sc">+</span> <span class="fu">log</span>(l_amnt) <span class="sc">+</span> </span>
<span id="cb54-3"><a href="#cb54-3"></a> <span class="fu">log</span>(income) <span class="sc">+</span> emp_len <span class="sc">+</span> home <span class="sc">+</span> sex <span class="sc">+</span></span>
<span id="cb54-4"><a href="#cb54-4"></a> region, <span class="at">family =</span> <span class="st">"binomial"</span>, <span class="at">data =</span> train)</span>
<span id="cb54-5"><a href="#cb54-5"></a><span class="co"># Loan status predictions for all test set elements.</span></span>
<span id="cb54-6"><a href="#cb54-6"></a>pred_logi_full <span class="ot"><-</span> <span class="fu">predict</span>(logi_full, <span class="at">newdata =</span> test, <span class="at">type =</span> <span class="st">"response"</span>)</span>
<span id="cb54-7"><a href="#cb54-7"></a><span class="co"># Look at the predictions range.</span></span>
<span id="cb54-8"><a href="#cb54-8"></a><span class="fu">range</span>(pred_logi_full)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 1.422469e-09 8.544424e-01</code></pre>
</div>
</div>
<p>Now, the <tt><code>pred_logi_full</code></tt> prediction range is wider. A wider range means that the <tt><code>loan_st</code></tt> predictions are now closer to 1. This is good because we need the model to be able to predict both no-defaults (0) and defaults (1). Let’s see a prediction comparison with respect to the rest of the models.</p>
<div class="cell">
<details class="code-fold">
<summary>Code</summary>
<div class="sourceCode cell-code" id="cb56"><pre class="sourceCode numberSource r number-lines code-with-copy"><code class="sourceCode r"><span id="cb56-1"><a href="#cb56-1"></a>pred_range <span class="ot"><-</span> <span class="fu">rbind</span>(<span class="st">"logi_age"</span> <span class="ot">=</span> <span class="fu">range</span>(pred_logi_age), </span>
<span id="cb56-2"><a href="#cb56-2"></a> <span class="st">"logi_int"</span> <span class="ot">=</span> <span class="fu">range</span>(pred_logi_int),</span>
<span id="cb56-3"><a href="#cb56-3"></a> <span class="st">"logi_multi"</span> <span class="ot">=</span> <span class="fu">range</span>(pred_logi_multi),</span>