rm(list=ls(all=T))
options(digits=4, scipen=12)
library(magrittr)
議題:議題:使用貸款人的資料,預測他會不會還款
【1.1 基礎機率】What proportion of the loans in the dataset were not paid in full?
loans = read.csv("loans.csv")
summary(loans)
credit.policy purpose int.rate installment log.annual.inc dti fico
Min. :0.000 all_other :2331 Min. :0.060 Min. : 15.7 Min. : 7.55 Min. : 0.00 Min. :612
1st Qu.:1.000 credit_card :1262 1st Qu.:0.104 1st Qu.:163.8 1st Qu.:10.56 1st Qu.: 7.21 1st Qu.:682
Median :1.000 debt_consolidation:3957 Median :0.122 Median :268.9 Median :10.93 Median :12.66 Median :707
Mean :0.805 educational : 343 Mean :0.123 Mean :319.1 Mean :10.93 Mean :12.61 Mean :711
3rd Qu.:1.000 home_improvement : 629 3rd Qu.:0.141 3rd Qu.:432.8 3rd Qu.:11.29 3rd Qu.:17.95 3rd Qu.:737
Max. :1.000 major_purchase : 437 Max. :0.216 Max. :940.1 Max. :14.53 Max. :29.96 Max. :827
small_business : 619 NA's :4
days.with.cr.line revol.bal revol.util inq.last.6mths delinq.2yrs pub.rec not.fully.paid
Min. : 179 Min. : 0 Min. : 0.0 Min. : 0.00 Min. : 0.000 Min. :0.000 Min. :0.00
1st Qu.: 2820 1st Qu.: 3187 1st Qu.: 22.7 1st Qu.: 0.00 1st Qu.: 0.000 1st Qu.:0.000 1st Qu.:0.00
Median : 4140 Median : 8596 Median : 46.4 Median : 1.00 Median : 0.000 Median :0.000 Median :0.00
Mean : 4562 Mean : 16914 Mean : 46.9 Mean : 1.57 Mean : 0.164 Mean :0.062 Mean :0.16
3rd Qu.: 5730 3rd Qu.: 18250 3rd Qu.: 71.0 3rd Qu.: 2.00 3rd Qu.: 0.000 3rd Qu.:0.000 3rd Qu.:0.00
Max. :17640 Max. :1207359 Max. :119.0 Max. :33.00 Max. :13.000 Max. :5.000 Max. :1.00
NA's :29 NA's :62 NA's :29 NA's :29 NA's :29
table(loans$not.fully.paid)
0 1
8045 1533
1533/nrow(loans)
[1] 0.1601
# 0.1600543
【1.2 檢查缺項】Which of the following variables has at least one missing observation?
# log.annual.inc
# days.with.cr.line
# revol.util
# inq.last.6mths
# delinq.2yrs
# pub.rec
【1.3 決定是否要補缺項】Which of the following is the best reason to fill in the missing values for these variables instead of removing observations with missing data?
missing = subset(loans, is.na(log.annual.inc) | is.na(days.with.cr.line) | is.na(revol.util) | is.na(inq.last.6mths) | is.na(delinq.2yrs) | is.na(pub.rec))
nrow(missing)
[1] 62
table(missing$not.fully.paid)
0 1
50 12
# We want to be able to predict risk for all borrowers, instead of just the ones with all data reported.
【1.4 補缺項工具】What best describes the process we just used to handle missing values?
# install.packages("mice")
library(mice)
set.seed(144)
vars.for.imputaton = setdiff(names(loans), "not.fully.paid")
imputed = complete(mice(loans[vars.for.imputaton]))
iter imp variable
1 1 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
1 2 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
1 3 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
1 4 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
1 5 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
2 1 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
2 2 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
2 3 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
2 4 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
2 5 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
3 1 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
3 2 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
3 3 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
3 4 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
3 5 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
4 1 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
4 2 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
4 3 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
4 4 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
4 5 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
5 1 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
5 2 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
5 3 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
5 4 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
5 5 log.annual.inc days.with.cr.line revol.util inq.last.6mths delinq.2yrs pub.rec
loans[vars.for.imputaton] = imputed
# We predicted missing variable values using the available independent variables for each observation.
【2.1 顯著性】Which independent variables are significant in our model?
set.seed(144)
library(caTools)
split = sample.split(loans$not.fully.paid, SplitRatio = 0.7)
train = subset(loans, split==T)
test = subset(loans, split==F)
loansLog = glm(not.fully.paid ~ . , data = train, family = "binomial")
summary(loansLog)
Call:
glm(formula = not.fully.paid ~ ., family = "binomial", data = train)
Deviance Residuals:
Min 1Q Median 3Q Max
-2.187 -0.621 -0.495 -0.361 2.639
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 9.15800765 1.55514067 5.89 0.0000000039 ***
credit.policy -0.34924658 0.10082598 -3.46 0.00053 ***
purposecredit_card -0.61439777 0.13440351 -4.57 0.0000048472 ***
purposedebt_consolidation -0.32165576 0.09182845 -3.50 0.00046 ***
purposeeducational 0.13578079 0.17527403 0.77 0.43853
purposehome_improvement 0.17435349 0.14791842 1.18 0.23851
purposemajor_purchase -0.48141854 0.20079306 -2.40 0.01650 *
purposesmall_business 0.41343357 0.14183237 2.91 0.00356 **
int.rate 0.62211379 2.08490225 0.30 0.76541
installment 0.00127297 0.00020918 6.09 0.0000000012 ***
log.annual.inc -0.43129368 0.07145262 -6.04 0.0000000016 ***
dti 0.00462735 0.00549967 0.84 0.40013
fico -0.00929381 0.00170831 -5.44 0.0000000532 ***
days.with.cr.line 0.00000219 0.00001588 0.14 0.89044
revol.bal 0.00000303 0.00000117 2.60 0.00928 **
revol.util 0.00191601 0.00153293 1.25 0.21134
inq.last.6mths 0.08073987 0.01586849 5.09 0.0000003617 ***
delinq.2yrs -0.08338381 0.06554209 -1.27 0.20330
pub.rec 0.33104300 0.11375811 2.91 0.00361 **
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 5896.6 on 6704 degrees of freedom
Residual deviance: 5487.4 on 6686 degrees of freedom
AIC: 5525
Number of Fisher Scoring iterations: 5
# credit.policy
# purpose2 (credit card)
# purpose3 (debt consolidation)
# purpose6 (major purchase)
# purpose7 (small business)
# installment
# log.annual.inc
# fico
# revol.bal
# inq.last.6mths
# pub.rec
【2.2 從回歸係數估計邊際效用】Consider two loan applications, which are identical other than the fact that the borrower in Application A has FICO credit score 700 while the borrower in Application B has FICO credit score 710. What is the value of Logit(A) - Logit(B)? What is the value of O(A)/O(B)?
# the difference of logits
-0.009317 * (700-710)
[1] 0.09317
# the ratio of odds
# exp(A + B + C) = exp(A)*exp(B)*exp(C)
exp(0.09317)
[1] 1.098
【2.3 混淆矩陣、正確率 vs 底線機率】What is the accuracy of the logistic regression model? What is the accuracy of the baseline model?
predicted.risk = predict(loansLog, newdata = test, type="response")
test$predicted.risk = predicted.risk
table(test$not.fully.paid, predicted.risk>0.5)
FALSE TRUE
0 2400 13
1 457 3
# test accuracy
accuracy = (2400+3)/nrow(test); accuracy
[1] 0.8364
# 0.8364
# baseline accuracy
table(train$not.fully.paid)
0 1
5632 1073
table(test$not.fully.paid)
0 1
2413 460
2413/nrow(test)
[1] 0.8399
# 0.8399
【2.4 ROC & AUC】Use the ROCR package to compute the test set AUC.
library(ROCR)
pred = prediction(test$predicted.risk, test$not.fully.paid)
as.numeric(performance(pred, "auc")@y.values)
[1] 0.6719
【3.1 高底線模型】The variable int.rate is highly significant in the bivariate model, but it is not significant at the 0.05 level in the model trained with all the independent variables. What is the most likely explanation for this difference?
bivariateModel = glm(not.fully.paid~ int.rate, data = train, family = "binomial")
summary(bivariateModel)
Call:
glm(formula = not.fully.paid ~ int.rate, family = "binomial",
data = train)
Deviance Residuals:
Min 1Q Median 3Q Max
-1.055 -0.627 -0.544 -0.436 2.291
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -3.673 0.169 -21.8 <2e-16 ***
int.rate 15.921 1.270 12.5 <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: 5896.6 on 6704 degrees of freedom
Residual deviance: 5734.8 on 6703 degrees of freedom
AIC: 5739
Number of Fisher Scoring iterations: 4
# int.rate is correlated with other risk-related variables, and therefore does not incrementally improve the model when those other variables are included.
【3.2 高底線模型的預測值】What is the highest predicted probability of a loan not being paid in full on the testing set? With a logistic regression cutoff of 0.5, how many loans would be predicted as not being paid in full on the testing set?
biPred = predict(bivariateModel, newdata = test, type = 'response')
max(biPred)
[1] 0.4266
# 0.4266
table(biPred>0.5)
FALSE
2873
# 0
【3.3 高底線模型的辨識率】What is the test set AUC of the bivariate model?
library(ROCR)
pred = prediction(biPred, test$not.fully.paid)
as.numeric(performance(pred, "auc")@y.values)
[1] 0.6239
【4.1 投資價值的算法】How much does a $10 investment with an annual interest rate of 6% pay back after 3 years, using continuous compounding of interest?
10*exp(0.06*3)
[1] 11.97
# 11.97
【4.2 投資獲利的算法,合約完成】While the investment has value c * exp(rt) dollars after collecting interest, the investor had to pay $c for the investment. What is the profit to the investor if the investment is paid back in full?
# c * exp(rt) - c
【4.3 投資獲利的算法,違約】Now, consider the case where the investor made a $c investment, but it was not paid back in full. Assume, conservatively, that no money was received from the borrower (often a lender will receive some but not all of the value of the loan, making this a pessimistic assumption of how much is received). What is the profit to the investor in this scenario?
# c * exp(rt) - c correct
# -c
【5.1 計算測試資料的實際投報率】What is the maximum profit of a $10 investment in any loan in the testing set?
test$profit = exp(test$int.rate*3) - 1
test$profit[test$not.fully.paid == 1] = -1
max(test$profit)*10
[1] 8.895
# 8.895
A simple investment strategy of equally investing in all the loans would yield profit $20.94 for a $100 investment. But this simple investment strategy does not leverage the prediction model we built earlier in this problem.
【6.1 高利率、高風險】What is the average profit of a $1 investment in one of these high-interest loans (do not include the $ sign in your answer)? What proportion of the high-interest loans were not paid back in full?
highInterest = subset(test, int.rate>=0.15)
mean(highInterest$profit)
[1] 0.2251
# 0.2251
table(highInterest$not.fully.paid)
0 1
327 110
110/nrow(highInterest)
[1] 0.2517
# 0.2517
【6.2 高利率之中的低風險】What is the profit of the investor, who invested $1 in each of these 100 loans? How many of 100 selected loans were not paid back in full?
cutoff = sort(highInterest$predicted.risk, decreasing=FALSE)[100]
selectedLoans = subset(highInterest, highInterest$predicted.risk <= cutoff)
sum(selectedLoans$profit)
[1] 31.28
# 31.28
table(selectedLoans$not.fully.paid)
0 1
81 19
# 19
【Q】利用我們建好的模型,你可以設計出比上述的方法獲利更高的投資方法嗎?請詳述你的作法?
#
#
#
#