-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProj2_report_MY_UG.Rmd
2069 lines (1478 loc) · 78 KB
/
Proj2_report_MY_UG.Rmd
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
---
title: "Classification Modeling on LendingClub's Loan Data"
author: "Uyemaa Gantulga, Ayush Meshram, Aakash Singh, and Melissa Yago"
date: "12/09/24"
output:
html_document:
code_folding: show
number_sections: false
toc: yes
toc_depth: 3
toc_float: yes
pdf_document:
toc: yes
toc_depth: '3'
---
```{r setup, include=F}
# Some of common RMD options (and the defaults) are:
# include=T, eval=T, echo=T, results='hide'/'asis'/'markup',..., collapse=F, warning=T, message=T, error=T, cache=T, fig.width=6, fig.height=4, fig.dim=c(6,4) #inches, fig.align='left'/'center','right',
knitr::opts_chunk$set(results="markup", warning = F, message = F)
# Can globally set option for number display format.
options(scientific=T, digits = 3)
# options(scipen=9, digits = 3)
library(dplyr)
library(ezids)
library(ggplot2)
library(data.table)
library(fmsb)
library(corrplot)
library(lubridate)
library(maps)
library(ggmap)
library(tidyverse)
library(forcats)
library(readr)
library(reshape2)
library(viridis)
library(ggcorrplot)
library(data.table)
library(psych)
library(randomForest)
```
### Data preparation
```{r}
# Read large CSV
data <- fread("C:\\Users\\uemaa\\Documents\\DS6101\\Fin\\Proj2\\cleaned_accepted_2013_to_2018Q4.csv")
df <- data[, c("issue_d", "loan_amnt", "int_rate", "grade", "sub_grade", "emp_length", "annual_inc", "dti", "fico_range_low", "fico_range_high", "last_fico_range_high", "last_fico_range_low", "open_acc_6m","loan_status")]
```
# Introduction
LendingClub is a financial services company that facilitates loan contracts. This analysis examines approved loan data (2013-2018) to identify factors that contribute to loan charge-offs.
**Dataset Overview**:
- **Observations**: 2.15 million approved loans
- **Goal**: Use predictive modeling to analyze factors affecting loan charge-offs.
Source: https://www.kaggle.com/datasets/wordsforthewise/lending-club
Github: https://github.com/aash1999/all-lending-club-loan-data
Ppt: https://docs.google.com/presentation/d/173CgDYyy9xvD72MpYmGiLR0wO9Vlwn3U/edit?usp=sharing&ouid=102489423949507971777&rtpof=true&sd=true
# Research Questions
1. **Features Impact**: Which combination of features from our
initial EDA (interest rate, grade, annual income, etc.)
provides the most reliable predictions of the 2013-2018 loan
data?
2. **Model Performance**: How do logistic regression and
random forest models compare in their ability to predict
loan charge-offs when trained on 2013-2015 data and
tested on holdout sets from 2013-2015 and 2016-2018 data?
3. **Prediction Accuracy Across Timeframes**: How accurately can
we predict loan charge-offs for loans issued between
2015-2018 that are still active and might charge-off in
future, using our 2013-2018 trained models from Question 2?
# Question #1: Features Impact
Which combination of features from our initial EDA (interest rate, grade, annual income, etc.) provides the most reliable predictions of the 2013-2018 loan data?
## Independent Variables:
This analysis focuses on the following variables:
1. **Loan Amount**: The total loan amount approved for the borrower.
2. **Interest Rate**: The interest rate associated with the loan.
3. **Grade**: The loan's credit grade assigned by LendingClub.
4. **Sub Grade**: A finer classification of the credit grade.
5. **DTI (Debt to Income Ratio)**: The borrower's monthly debt payments divided by their monthly income.
6. **Employment Length**: The borrower's duration of employment, measured in years.
7. **Annual Income**: The borrower's yearly income.
8. **open_acc_6m**: Number of open accounts the borrower had in the last six months.
9. **FICO Scores**:
- **FICO Range High/Low**: The range of the borrower's credit score at the time of loan issuance.
- **Latest FICO Range High/Low**: The most recent range of the borrower's credit score.
## Dependent Variable:
- **Loan Status**: The outcome of the loan, categorized as either "Charged Off" (defaulted loans) or "Fully Paid" (successfully repaid loans).
---
## Significance of Variables
Each independent variable contributes to the prediction of loan charge-offs:
- **Loan Amount**: Larger loans may have higher risk due to greater financial burden.
- **Interest Rate**: Higher interest rates often correlate with riskier loans.
- **Grade and Sub Grade**: Indicators of creditworthiness; lower grades suggest higher risk.
- **DTI**: High DTI ratios indicate borrowers with financial strain, increasing default risk.
- **Employment Length**: Longer employment may indicate financial stability.
- **Annual Income**: Higher income reduces the likelihood of default.
- **open_acc_6m**: Indicates the borrower’s recent credit activity, which could reflect their financial behavior.
- **FICO Scores**: Key indicators of a borrower’s creditworthiness.
## Loan Analysis
### Loan Repayment Rate by Grade
```{r loan-repayment-rate, echo=FALSE, out.width="80%", fig.align="center"}
knitr::include_graphics("C:\\Users\\uemaa\\Documents\\DS6101\\Fin\\Proj2\\images\\loan_repayment_grade.png")
```
The bar chart below shows the repayment rates across different loan grades.
It highlights that higher grades (e.g., A and B) have significantly better repayment rates compared to lower grades (e.g., F and G).
### Comparison of Loan Variables (2014 vs. 2017)
The radar chart below compares various loan characteristics (e.g., interest rates, FICO scores, DTI) between 2014 and 2017. This helps us observe changes in borrower profiles over time.
```{r}
knitr::include_graphics("C:\\Users\\uemaa\\Documents\\DS6101\\Fin\\Proj2\\images\\Comp_loan_variables.png")
```
Key Insight:
FICO scores and debt-to-income ratios remained relatively stable.
Interest rates show slight variation, reflecting adjustments in lending policies.
### Distribution of Loan Amounts
The histogram below represents the distribution of loan amounts for accepted loans. Most loans fall between $5,000 and $20,000, with a peak at $10,000.
```{r}
knitr::include_graphics("C:\\Users\\uemaa\\Documents\\DS6101\\Fin\\Proj2\\images\\distribution_accepted.png")
```
Key Insight:
Loan amounts are concentrated around the $10,000 mark.
Larger loans ($30,000 or more) are less frequent but still significant in volume.
---
### Initial Findings from EDA
The exploratory data analysis (EDA) revealed the following key insights:
1. **Interest Rate and Grade** are strongly associated with loan outcomes:
- Higher grades (A, B) correspond to better repayment rates.
- Higher interest rates correlate with increased default risk.
2. **Annual Income and DTI** provide moderate predictive power:
- Borrowers with higher incomes and lower DTI ratios exhibit fewer charge-offs.
3. **FICO Scores** are critical predictors:
- Borrowers with higher FICO ranges are significantly less likely to default.
---
### Feature Selection and Justification
Based on EDA and initial modeling results:
- All selected features are statistically significant predictors of loan outcomes.
- **FICO Scores, Interest Rate, and Grade** are the strongest predictors, providing high reliability for predicting loan charge-offs.
- Secondary predictors, such as **Loan Amount, Annual Income, and Employment Length**, add incremental value to the model.
These features form the foundation for the subsequent predictive modeling discussed in the next sections.
# Question 2: Model Performance
How do different classification models (logistic regression and classification tree) compare in their ability to predict loan charge-offs when trained on 2013-2015 data and tested on holdout sets from 2013-2015 and 2016-2018 data?
## Overview
To compare the performance of logistic regression and random forest models in predicting loan charge-offs, we trained both models on data from 2013-2015 and tested them on two holdout datasets:
1. **2013-2015 Test Set**: To evaluate in-sample performance.
2. **2016-2018 Test Set**: To evaluate out-of-sample performance and generalizability.
## Data Preparation
The dataset was split into training (70%), evaluation (15%), and test (15%) sets. Missing values were imputed, and numeric features were normalized using MinMax scaling.
```{r data-preparation, echo=TRUE}
# Splitting the dataset
library(caret)
set.seed(123)
split <- createDataPartition(df$loan_status, p = 0.7, list = FALSE)
train_data <- df[split, ]
temp_data <- df[-split, ]
split_eval <- createDataPartition(temp_data$loan_status, p = 0.5, list = FALSE)
eval_data <- temp_data[split_eval, ]
test_data <- temp_data[-split_eval, ]
# Check dimensions
dim(train_data)
dim(eval_data)
dim(test_data)
```
```{r, echo=TRUE}
#For Question #2
#Load 2013-2015 Train Data
train_data <-read.csv("C:\\Users\\uemaa\\Documents\\DS6101\\Fin\\Proj2\\data_2013_2015_train.csv")
#Convert Loan Status to Numeric Values \ 1= Charged Off 0 = Fully Paid
train_data$loan_status <- ifelse(train_data$loan_status == "Charged Off", 1,0)
#Load Test Data 2013-2015
test_data <-read.csv("C:\\Users\\uemaa\\Documents\\DS6101\\Fin\\Proj2\\data_2013_2015_test.csv")
#Convert Loan Status to Numeric Values \ 1= Charged Off 0 = Fully Paid
test_data$loan_status <- ifelse(test_data$loan_status == "Charged Off", 1,0)
#Load Test Data 2016-2018
test_data_2 <-read.csv("C:\\Users\\uemaa\\Documents\\DS6101\\Fin\\Proj2\\data_2016_2018_test.csv")
#Convert Loan Status to Numeric Values \ 1= Charged Off 0 = Fully Paid
test_data_2$loan_status <- ifelse(test_data_2$loan_status == "Charged Off", 1,0)
#For Question #3
#Load Active Loans Data
active_data <-read.csv("C:\\Users\\uemaa\\Documents\\DS6101\\Fin\\Proj2\\predict.csv")
#Load 2013-2018 Train Data
all_train_data <-read.csv("C:\\Users\\uemaa\\Documents\\DS6101\\Fin\\Proj2\\train.csv")
#Convert Loan Status to Numeric Values \ 1= Charged Off 0 = Fully Paid
all_train_data$loan_status <- ifelse(all_train_data$loan_status == "Charged Off", 1,0)
```
## Logistic Regression Model Performance
### Logistic Model Training on 2013-2015 Data
The logistic regression model was trained on the 2013-2015 data with the following independent variables:
- Loan Amount
- Interest Rate
- Grade
- Sub Grade
- DTI
- Employment Length
- Annual Income
**Key Insights from Training**:
1. **Statistical Significance**: All predictors included in the model were statistically significant (p < 0.05), indicating their relevance to predicting loan charge-offs.
2. **Impact of Predictors** (Rounded Coefficients):
- **Loan Amount (0.13)**: A $1 increase in the loan amount slightly increases the likelihood of charge-offs.
- **Interest Rate (-0.62)**: Higher interest rates are associated with a decreased likelihood of charge-offs.
- **Grade G (5.29)**: Loans with Grade G are significantly more likely to charge off compared to Grade A loans.
- **Employment Length (< 1 Year, -0.24)**: Borrowers with less than one year of employment are less likely to charge off.
```{r, echo=TRUE}
#Logistic Regression Model
log_model <-glm(loan_status ~ loan_amnt + int_rate + grade + sub_grade + dti + emp_length + annual_inc, data = train_data, family = binomial)
#Summary of Model
summary(log_model)
```
### Logistic Model Evaluation on 2013-2015 Test Data
The trained logistic regression model was evaluated using test data from 2013-2015.
Results:
Confusion Matrix:
87,900 True Negatives (Fully Paid loans correctly predicted)
19,849 False Negatives (Charged Off loans misclassified as Fully Paid)
529 False Positives (Fully Paid loans misclassified as Charged Off)
527 True Positives (Charged Off loans correctly predicted)
Performance Metrics:
Accuracy: 81.3% (The model correctly classifies 81.3% of loans.)
Sensitivity: 2.49% (Very low sensitivity indicates the model struggles to identify charge-offs.)
Specificity: 99.43% (The model excels at identifying fully paid loans.)
AUC: 0.705 (Moderate ability to distinguish between Charged Off and Fully Paid loans.)
ROC Curve & AUC
AUC 0.705: On average, the model has a 70.5% chance of distinguishing between a loan that gets charged off and one that is fully paid. Overall, this model has a moderate ability to distinguish between charged off and fully paid loans when applied to unseen data from 2013-2015.
```{r, echo=TRUE}
#libraries
library(caret)
library(pROC)
#Predict on test data
log_predict <- predict(log_model, test_data, type = "response")
#Convert Probabilities to Class
log_predict_class <- ifelse(log_predict > 0.5, 1, 0)
#Covert Predicted and Actual to Factors with Same Levels
log_predict_class <-factor(log_predict_class, levels = c(0,1)) # Predicted Classes
test_data$loan_status <-factor(test_data$loan_status, levels = c(0,1)) # Actual Classes
#Confusion Matrix
con_matrix <- confusionMatrix(as.factor(log_predict_class), test_data$loan_status)
print(con_matrix)
#ROC Curve and AUC
roc_curve <-roc(test_data$loan_status, as.numeric(log_predict))
auc_value <- auc(roc_curve)
print(auc_value)
plot(roc_curve)
```
### Logistic Model Evaluation on 2016-2018 Test Data
The same model was evaluated on out-of-sample test data (2016-2018) to assess its generalizability.
Results:
Confusion Matrix:
60,146 True Negatives
17,415 False Negatives
188 False Positives
177 True Positives
Performance Metrics:
Accuracy: 77.4% (Slight decrease compared to in-sample performance.)
Sensitivity: 1.12% (The model struggles even more to identify charge-offs.)
Specificity: 99.69% (The model still performs well for fully paid loans.)
AUC: 0.694 (Moderate ability to distinguish outcomes.)
```{r, echo=TRUE}
#libraries
library(caret)
library(pROC)
#Predict on test data
log_predict_2 <- predict(log_model, test_data_2, type = "response")
#Convert Probabilities to Class
log_predict_class_2 <- ifelse(log_predict_2 > 0.5, 1, 0)
#Covert Predicted and Actual to Factors with Same Levels
log_predict_class_2 <-factor(log_predict_class_2, levels = c(0,1)) # Predicted Classes
test_data_2$loan_status <-factor(test_data_2$loan_status, levels = c(0,1)) # Actual Classes
#Confusion Matrix
con_matrix_2 <- confusionMatrix(as.factor(log_predict_class_2), test_data_2$loan_status)
print(con_matrix_2)
#ROC Curve and AUC
roc_curve_2 <-roc(test_data_2$loan_status, as.numeric(log_predict_2))
auc_value_2 <- auc(roc_curve_2)
print(auc_value_2)
plot(roc_curve_2)
```
```{R}
# Get numeric columns
numeric_cols <- names(train_data)[sapply(train_data, is.numeric)]
# Set up the plotting area
par(mfrow = c(3, 3)) # Creates a 3x3 grid of plots
# Simple histograms
for(col in numeric_cols) {
hist(train_data[[col]],
main = col,
xlab = col,
col = "lightblue")
}
# Reset plotting parameters
par(mfrow = c(1, 1))
```
The provided code snippet creates histograms for each numeric column in the train_data dataset. It first identifies the numeric columns using sapply() and is.numeric(). Then, it sets up a 3x3 grid of plots using par(mfrow = c(3, 3)) to display multiple histograms on a single page. The code iterates over each numeric column using a for loop, creating a histogram with the column name as the title and x-axis label, and "lightblue" as the fill color. Finally, it resets the plotting parameters with par(mfrow = c(1, 1)). This code provides a quick visual summary of the distribution of numeric variables in the dataset.
```{r}
missing_data <- function(df) {
# Store original dimensions
original_rows <- nrow(df)
# Step 1: Remove rows with missing loan_status
df <- df[!is.na(df$loan_status), ]
rows_after_status <- nrow(df)
# Step 2: Identify numeric and categorical columns
numeric_cols <- sapply(df, is.numeric)
categorical_cols <- sapply(df, function(x) is.factor(x) | is.character(x))
# Step 3: Median imputation for numeric columns
for(col in names(df)[numeric_cols]) {
if(any(is.na(df[[col]]))) {
col_median <- median(df[[col]], na.rm = TRUE)
df[[col]][is.na(df[[col]])] <- col_median
print(paste("Imputed", sum(is.na(df[[col]])), "missing values in", col, "with median:", round(col_median, 2)))
}
}
# Step 4: Mode imputation for categorical columns
for(col in names(df)[categorical_cols]) {
if(any(is.na(df[[col]]))) {
# Calculate mode (most frequent value)
mode_val <- names(sort(table(df[[col]]), decreasing = TRUE))[1]
df[[col]][is.na(df[[col]])] <- mode_val
print(paste("Imputed", sum(is.na(df[[col]])), "missing values in", col, "with mode:", mode_val))
}
}
# Print summary of cleaning
print("\nCleaning Summary:")
print(paste("Original number of rows:", original_rows))
print(paste("Rows removed due to missing loan_status:", original_rows - rows_after_status))
print(paste("Final number of rows:", nrow(df)))
return(df)
}
create_features <- function(df, poly_degree) {
# Store original dataframe
result_df <- df
# Get numeric columns except target (loan_status)
numeric_cols <- names(df)[sapply(df, is.numeric)]
numeric_cols <- numeric_cols[numeric_cols != "loan_status"]
# 1. Create interaction terms
cat("Creating interaction terms...\n")
if(length(numeric_cols) >= 2) { # Need at least 2 columns for interactions
# Get all possible pairs of columns
pairs <- combn(numeric_cols, 2)
# Create interaction terms
for(i in 1:ncol(pairs)) {
col1 <- pairs[1,i]
col2 <- pairs[2,i]
new_col_name <- paste0("interaction_", col1, "_", col2)
result_df[[new_col_name]] <- df[[col1]] * df[[col2]]
}
}
# 2. Create polynomial terms
cat("Creating polynomial terms...\n")
for(col in numeric_cols) {
for(degree in 2:poly_degree) { # Start from degree 2 since degree 1 is original
new_col_name <- paste0("poly_", col, "_degree_", degree)
result_df[[new_col_name]] <- df[[col]]^degree
}
}
# Print summary of new features
n_interactions <- ncol(result_df) - ncol(df)
cat("\nFeature Engineering Summary:\n")
cat("Original features:", length(numeric_cols), "\n")
cat("New features created:", n_interactions, "\n")
cat("Total features:", ncol(result_df), "\n")
return(result_df)
}
train_data <- missing_data(train_data)
test_data <- missing_data(test_data)
active_data <- missing_data(active_data)
# Example usage:
train_data <- create_features(train_data, poly_degree = 2)
test_data <- create_features(test_data, poly_degree = 2)
active_data <- create_features(active_data, poly_degree = 2)
```
Missing Data Handling:
We developed a custom missing_data function to preprocess the dataset:
Rows with missing values in the loan_status column were removed.
For numeric columns, missing values were imputed with the median of the respective column.
For categorical columns, missing values were imputed using the mode (most frequent value) of the column. This ensured a complete dataset with no missing values, maintaining the original data size as no rows required removal.
Feature Engineering:
We implemented a create_features function to enrich the dataset:
Interaction Terms: Created pairwise interaction features for numeric columns to capture relationships between variables.
Polynomial Features: Generated polynomial terms of degree 2 for numeric columns, capturing non-linear relationships.
This resulted in significant expansion of the feature set:
For the training dataset, 55 new features were added, increasing the total from 10 to 69.
For the active dataset, 2,090 new features were generated, bringing the total to 2,159.
These steps aimed to improve the predictive power of the model by providing it with a richer and more diverse feature set.
```{R}
# Load required packages
library(caret)
library(pROC)
library(glmnet)
# 1. Data Preparation and Cleaning
# First, handle missing values
numeric_cols <- sapply(train_data, is.numeric)
for(col in names(train_data)[numeric_cols]) {
train_data[[col]][is.na(train_data[[col]])] <- median(train_data[[col]], na.rm = TRUE)
test_data[[col]][is.na(test_data[[col]])] <- median(train_data[[col]], na.rm = TRUE)
}
# Fix the loan_status encoding
# First, ensure it's numeric
train_data$loan_status <- as.numeric(as.character(train_data$loan_status))
test_data$loan_status <- as.numeric(as.character(test_data$loan_status))
# Then convert to factor with proper levels
train_data$loan_status <- factor(train_data$loan_status,
levels = c(0, 1),
labels = c("Fully Paid", "Charged-Off"))
test_data$loan_status <- factor(test_data$loan_status,
levels = c(0, 1),
labels = c("Fully Paid", "Charged-Off"))
# For training data
if("issue_d" %in% colnames(train_data)) {
train_data <- subset(train_data, select = -c(issue_d))
cat("issue_d column removed from training data\n")
} else {
cat("issue_d column not found in training data\n")
}
# For test data
if("issue_d" %in% colnames(test_data)) {
test_data <- subset(test_data, select = -c(issue_d))
cat("issue_d column removed from test data\n")
} else {
cat("issue_d column not found in test data\n")
}
```
1. Handling Missing Values
Objective: Ensure no missing values remain in numeric columns to avoid disruptions during model training.
Process:
For each numeric column in the training and testing datasets, missing values were replaced with the median of the respective column in the training dataset. This ensures consistency and avoids data leakage.
2. Encoding the Target Variable
Objective: Prepare the target variable (loan_status) for classification tasks.
Process:
Converted loan_status to a numeric type to remove formatting issues.
Recoded loan_status as a factor with meaningful labels:
Fully Paid (class 0)
Charged-Off (class 1)
3. Removing Unnecessary Columns
Objective: Eliminate irrelevant or redundant features to simplify the dataset.
Process:
Checked for the presence of the issue_d column, which may not contribute to the model's performance.
Removed the issue_d column from both training and testing datasets to streamline data processing.
4. Results:
Missing values were effectively handled, ensuring a complete dataset.
The target variable was prepared for binary classification with clear labels.
Redundant columns were identified and removed, reducing potential noise in the model.
```{r}
# 2. Set up cross-validation
ctrl <- trainControl(
method = "cv",
number = 5,
classProbs = TRUE,
summaryFunction = twoClassSummary,
sampling = "down",
verboseIter = TRUE
)
# 3. Grid for hyperparameter tuning
grid <- expand.grid(
alpha = c(0, 0.5, 1),
lambda = seq(0.001, 0.1, length.out = 5)
)
levels(train_data$loan_status) <- make.names(levels(train_data$loan_status))
# 4. Train improved model
set.seed(123)
improved_model <- train(
loan_status ~ .,
data = train_data,
method = "glmnet",
metric = "ROC",
trControl = ctrl,
tuneGrid = grid,
family = "binomial"
)
```
Cross-Validation: Used 5-fold cross-validation with ROC AUC as the metric and applied downsampling to address class imbalance in loan_status.
Hyperparameter Tuning: Created a grid to optimize alpha (L1/L2 regularization balance) and lambda (regularization strength) for the glmnet model.
Model Training: Trained a regularized logistic regression (glmnet) with binomial family for binary classification, evaluating performance using ROC AUC across hyperparameter combinations.
Outcome: Developed a robust model with enhanced generalizability through cross-validation and tuning.
```{r}
# 5. Make predictions
improved_predict <- predict(improved_model, test_data, type = "prob")[,"Charged.Off"]
# Find optimal threshold
roc_obj <- roc(test_data$loan_status, improved_predict)
optimal_coords <- coords(roc_obj, "best", ret = "threshold")
optimal_threshold <- optimal_coords$threshold
# Create class predictions using optimal threshold
improved_predict_class <- factor(
ifelse(improved_predict > optimal_threshold, "Charged.Off", "Fully.Paid"),
levels = c("Charged.Off", "Fully.Paid")
)
# 6. Model Evaluation
# Confusion Matrix
levels(test_data$loan_status) <- make.names(levels(test_data$loan_status))
improved_cm <- confusionMatrix(improved_predict_class, test_data$loan_status)
print(improved_cm)
# ROC and AUC
improved_roc <- roc(test_data$loan_status, improved_predict)
improved_auc <- auc(improved_roc)
print(paste("AUC:", round(improved_auc, 4)))
# 7. Visualizations
# ROC curve
plot(improved_roc, main = "ROC Curve for Improved Model")
# Feature importance
importance <- varImp(improved_model)
plot(importance, top = 10, main = "Top 10 Most Important Features")
# 8. Print detailed metrics
cat("\nDetailed Performance Metrics:\n")
cat("Accuracy:", round(improved_cm$overall['Accuracy'], 4), "\n")
cat("Sensitivity:", round(improved_cm$byClass['Sensitivity'], 4), "\n")
cat("Specificity:", round(improved_cm$byClass['Specificity'], 4), "\n")
cat("Precision:", round(improved_cm$byClass['Pos Pred Value'], 4), "\n")
cat("F1 Score:", round(2 * (improved_cm$byClass['Sensitivity'] * improved_cm$byClass['Pos Pred Value']) /
(improved_cm$byClass['Se+nsitivity'] + improved_cm$byClass['Pos Pred Value']), 4), "\n")
```
Predictions and Threshold Optimization: Predictions were made on the test dataset, and the optimal threshold for classification was determined using the ROC curve to balance sensitivity and specificity effectively.
Confusion Matrix and Metrics:
The confusion matrix showed Accuracy at 85.7%, with Sensitivity (84.5%) and Specificity (90.9%), indicating strong performance in identifying both Fully Paid and Charged Off loans.
The model's Precision for predicting the Fully Paid class was 97.6%, confirming its reliability in minimizing false positives.
AUC Score: The model achieved an AUC of 0.936, demonstrating excellent discrimination capability between the two classes.
Feature Importance and Visualization: The ROC curve was plotted to illustrate model performance, and the top 10 most important features contributing to predictions were identified and visualized.
Summary: The improved model provided robust performance metrics, validating its effectiveness for loan status classification tasks.
Visualization:
The ROC curve was plotted to visualize the trade-off between true positive and false positive rates.
A feature importance chart was generated, highlighting the top 10 features contributing to the model's predictions.
Key Findings: The improved model demonstrated strong classification performance with balanced sensitivity and specificity, showcasing its effectiveness in predicting loan_status.
```{r, echo=TRUE}
#libraries
library(caret)
library(pROC)
#Predict on test data
log_predict_2 <- predict(log_model, test_data_2, type = "response")
#Convert Probabilities to Class
log_predict_class_2 <- ifelse(log_predict_2 > 0.5, 1, 0)
#Covert Predicted and Actual to Factors with Same Levels
log_predict_class_2 <-factor(log_predict_class_2, levels = c(0,1)) # Predicted Classes
test_data_2$loan_status <-factor(test_data_2$loan_status, levels = c(0,1)) # Actual Classes
#Confusion Matrix
con_matrix_2 <- confusionMatrix(as.factor(log_predict_class_2), test_data_2$loan_status)
print(con_matrix_2)
#ROC Curve and AUC
roc_curve_2 <-roc(test_data_2$loan_status, as.numeric(log_predict_2))
auc_value_2 <- auc(roc_curve_2)
print(auc_value_2)
plot(roc_curve_2)
```
```{r}
# Examine the structure and missing values
str(test_data_2)
colSums(is.na(test_data_2))
# Clean the data
test_data_2_clean <- na.omit(test_data_2)
# Check if loan_status needs recoding (if it's 1,2 instead of 0,1)
unique(test_data_2_clean$loan_status)
```
```{r}
# Load required libraries
library(caret)
library(pROC)
library(glmnet)
library(recipes)
# Keep track of loan_status levels
print("Initial loan_status levels:")
print(levels(test_data_2$loan_status))
# Handle missing values
test_data_2$dti[is.na(test_data_2$dti)] <- median(test_data_2$dti, na.rm = TRUE)
test_data_2$open_acc_6m[is.na(test_data_2$open_acc_6m)] <- median(test_data_2$open_acc_6m, na.rm = TRUE)
# Remove rows with any remaining NA values
test_data_2 <- na.omit(test_data_2)
# Create recipe for feature engineering
recipe_obj <- recipe(loan_status ~ ., data = test_data_2) %>%
step_rm(issue_d) %>%
step_interact(terms = ~ loan_amnt:int_rate + loan_amnt:dti + int_rate:dti) %>%
step_poly(loan_amnt, int_rate, dti, degree = 2) %>%
step_dummy(all_nominal_predictors()) %>%
step_normalize(all_numeric_predictors())
# Prepare the data
prepared_data <- prep(recipe_obj) %>%
bake(new_data = NULL)
# Set up cross-validation
ctrl <- trainControl(
method = "cv",
number = 5,
classProbs = TRUE,
summaryFunction = twoClassSummary,
savePredictions = TRUE,
verboseIter = TRUE
)
# Create parameter grid
grid <- expand.grid(
alpha = seq(0, 1, by = 0.5),
lambda = 10^seq(-4, -1, length.out = 5)
)
# Split data into predictors and response
x_matrix <- as.matrix(prepared_data %>% select(-loan_status))
y_vector <- prepared_data$loan_status
y_vector <- factor(y_vector, levels = c(0, 1), labels = c("Fully.Paid", "charged.Off"))
# Train model
set.seed(123)
tuned_model <- train(
x = x_matrix,
y = y_vector,
method = "glmnet",
trControl = ctrl,
tuneGrid = grid,
metric = "ROC"
)
# Print best parameters
print("Best Tuning Parameters:")
print(tuned_model$bestTune)
```
Data Cleaning and Feature Engineering: Missing values for key predictors (dti and open_acc_6m) were imputed using their respective medians, and rows with remaining missing values were removed. Feature interactions and polynomial transformations were introduced for loan_amnt, int_rate, and dti. Categorical variables were encoded into dummy variables, and all numeric predictors were normalized to improve model performance.
Cross-Validation and Hyperparameter Tuning: A 5-fold cross-validation was performed using glmnet to identify the best combination of alpha (elastic net mixing parameter) and lambda (regularization strength). The parameter grid spanned values of alpha (0, 0.5, 1) and logarithmic scaling of lambda.
Results: After evaluating multiple combinations, the best tuning parameters were determined as alpha = 0.5 and lambda = 0.0001. This model was then trained on the full training set to optimize predictions.
```{r}
# Make predictions
predictions_prob <- predict( tuned_model, newdata = x_matrix, type = "prob")
predictions_class <- predict(tuned_model, newdata = x_matrix)
# Verify predictions structure
print("Structure of predictions:")
print(str(predictions_class))
print(str(y_vector))
# Generate confusion matrix
conf_matrix <- confusionMatrix(predictions_class, y_vector)
print("Confusion Matrix and Performance Metrics:")
print(conf_matrix)
# Calculate ROC and AUC
roc_obj <- roc(y_vector, predictions_prob[,"charged.Off"])
auc_value <- auc(roc_obj)
print(paste("AUC:", round(auc_value, 3)))
# Plot ROC curve
plot(roc_obj, main = "ROC Curve")
# Print detailed metrics
metrics <- data.frame(
Metric = c("Accuracy", "Sensitivity", "Specificity", "Precision", "AUC"),
Value = c(
conf_matrix$overall["Accuracy"],
conf_matrix$byClass["Sensitivity"],
conf_matrix$byClass["Specificity"],
conf_matrix$byClass["Pos Pred Value"],
auc_value
)
)
print("Detailed Performance Metrics:")
print(metrics)
# Variable importance
importance <- varImp(tuned_model)
print("Variable Importance:")
print(importance)
```
Confusion Matrix: The confusion matrix shows that the model successfully predicted 58,227 instances of "Fully.Paid" and 14,760 instances of "Charged.Off". The model achieved an accuracy of 93.6%, significantly outperforming the baseline accuracy of 77.4%.
Performance Metrics: Key performance metrics include:
Accuracy: 93.6%
Sensitivity: 96.4% (true positive rate for "Fully.Paid")
Specificity: 83.8% (true negative rate for "Charged.Off")
Precision: 95.3% (positive predictive value)
AUC: 0.968, indicating excellent model discrimination between the two classes.
Variable Importance: The analysis reveals the most influential variables in the model's decision-making process, which are critical for understanding the factors driving loan repayment predictions.
These results demonstrate that the tuned model performs well in classifying loan statuses and can be used for reliable decision-making in financial applications.
Interpretation:
The model’s performance declines slightly on out-of-sample data, likely due to differences in borrower behavior or economic conditions after 2015.
Improvements in feature selection or training data updates could improve generalizability.
To improve predictions, the following are considered:
Adjusting the probability threshold (e.g., >0.7 for higher confidence in classifying charged off loans).
Incorporating additional predictors (e.g., FICO scores or recent credit activity).
Combining with more complex models like Random Forests, which handle non-linear relationships and imbalanced classes better.
## Random Forest Model
### Overview
The Random Forest model was trained on 2013-2018 data and applied to predict loan charge-offs for active loans issued between 2015-2018. This method leverages Random Forest’s ability to handle:
- Non-linear relationships
- Imbalanced classes
- Feature importance analysis
- Regularization and robustness to noisy data
### Data Preparation
#### Handling Missing Values
1. **Numerical Variables**: Imputed using KNN imputation.
2. **Categorical Variables**: Imputed using mode.
3. Removed rows with missing `loan_status`.
#### Data Splitting
The dataset was split into:
- **Training Set**: 70%
- **Evaluation Set**: 15%
- **Test Set**: 15%
```{r}
train_df_path = "C:\\Users\\uemaa\\Documents\\DS6101\\Fin\\Proj2\\train.csv"
eval_df_path = "C:\\Users\\uemaa\\Documents\\DS6101\\Fin\\Proj2\\eval.csv"
test_df_path = "C:\\Users\\uemaa\\Documents\\DS6101\\Fin\\Proj2\\test.csv"
predict_df_path = "C:\\Users\\uemaa\\Documents\\DS6101\\Fin\\Proj2\\predict.csv"
train_df = fread(train_df_path)
eval_df = fread(eval_df_path)
test_df = fread(test_df_path)
predict_df = fread(predict_df_path)
target_column <- "loan_status"
```
### Class Distribution
```{r}
loan_status_counts <- table(train_df$loan_status)
loan_status_percentages <- round(100 * loan_status_counts / sum(loan_status_counts), 1)
loan_status_df <- data.frame(
status = names(loan_status_counts),
count = as.numeric(loan_status_counts),
percentage = loan_status_percentages
)
ggplot(loan_status_df, aes(x = "", y = count, fill = status)) +
geom_bar(stat = "identity", width = 1) +
coord_polar(theta = "y") +
labs(title = "Distribution of Charged Off vs Fully Paid Loans") +
theme_void() +
scale_fill_manual(values = c("Charged Off" = "red", "Fully Paid" = "green")) +
geom_text(aes(label = paste0(loan_status_df$percentage, "%")), position = position_stack(vjust = 0.5)) # Add percentages
```
Preparation of Data
```{r}
describe_df <- function(df){
print(summary(df))
print(describe(df))
print(colnames(df))
sapply(df, class)
missing_percentage <- sapply(df, function(x) sum(is.na(x)) / nrow(df) * 100)
missing_percentage_df <- data.frame(Column = names(missing_percentage),
Missing_Percentage = missing_percentage)
print(missing_percentage_df)
}
prepare_and_clean_data <- function(df) {
if (inherits(df, "data.table")) {
df <- as.data.frame(df)
}
if (!is.data.frame(df)) {
stop("Input is not a dataframe")
}
if ("loan_status" %in% names(df)) {
df <- df[!is.na(df$loan_status), ]
df$loan_status <- factor(df$loan_status)
}
if ("issue_d" %in% names(df)) {
df <- df[, !(names(df) %in% "issue_d")]
}
if ("grade" %in% names(df)) {
df$grade <- factor(df$grade)
}
if ("sub_grade" %in% names(df)) {
df$sub_grade <- factor(df$sub_grade)
}
if ("emp_length" %in% names(df)) {
df$emp_length <- factor(df$emp_length)
}