-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathModelling 2.Rmd
320 lines (259 loc) · 8.77 KB
/
Modelling 2.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
---
title: "Analysis v2"
author: "Deepak & Shruti"
date: "30 July 2017"
output:
html_document: default
pdf_document: default
---
#Work on Original Dataset
## Data Reading:
```{r}
library(readr)
Datav2 <- read_delim("Data/finalData.csv",
";", escape_double = FALSE, trim_ws = TRUE)
```
## Data Stats
```{r}
Datav2$InterestType <- as.factor(Datav2$InterestType)
Datav2$MortgageType <- as.factor(Datav2$MortgageType)
Datav2$NewLoan <- as.factor(Datav2$NewLoan)
Datav2$ProbationaryLoans <- as.factor(Datav2$ProbationaryLoans)
Datav2$LTVCategory <- as.factor(Datav2$LTVCategory)
Datav2$InArrears <- as.factor(Datav2$InArrears)
#Datav2$County <- as.factor(Datav2$County)
Datav2$DefaultedLoans <- as.factor(Datav2$DefaultedLoans)
m1 <- Datav2
m2 <- Datav2
m3 <- Datav2
```
##Data Prepration
```{r}
#Datav2$CreditRating <- as.factor(Datav2$CreditRating)
Datav2$InterestType <- as.factor(Datav2$InterestType)
Datav2$MortgageType <- as.factor(Datav2$MortgageType)
Datav2$NewLoan <- as.factor(Datav2$NewLoan)
Datav2$ProbationaryLoans <- as.factor(Datav2$ProbationaryLoans)
Datav2$LTVCategory <- as.factor(Datav2$LTVCategory)
Datav2$InArrears <- as.factor(Datav2$InArrears)
#Datav2$County <- as.factor(Datav2$County)
Datav2$DefaultedLoans <- as.factor(Datav2$DefaultedLoans)
#Datav2$LoanBalance <- scale(Datav2$LoanBalance)
#Datav2$PropertyValue <- scale(Datav2$PropertyValue)
#Datav2$InterestIncome <-scale(Datav2$InterestIncome)
#Datav2$AnnualPYMT <-scale(Datav2$AnnualPYMT)
#str(Datav2)
```
##Subsetting Train and Test Datasets
```{r}
set.seed(100)
dataPartition = sample(2,nrow(Datav2),replace=TRUE,prob=c(0.7,0.3))
trainDatav2 <- Datav2[dataPartition ==1,]
testDatav2 <- Datav2[dataPartition ==2,]
```
##GLM
### Model trained with all variables
```{r}
#m2 <- glm(DefaultedLoans ~., family = "binomial", data = trainDatav2)
#step(m2)
```
###Building Simple GLM Model
```{r}
simpleglmv2 <- glm(DefaultedLoans ~ CreditRating + InterestIncome +
PropertyValue + LoanBalance + AnnualPYMT + LTV +
InterestType + NewLoan + ProbationaryLoans + MortgageYears +
MortgageType + InArrears + County + AddressLatitude + AddressLongitude,
family = "binomial", data = trainDatav2)
summary(simpleglmv2)
save(simpleglmv2, file = "Model/simpleglmv2.rda")
```
###Running simple GLM Model on test data of predict loan default
```{r}
testDatav2$prediction <- predict(simpleglmv2, newdata=testDatav2, type="response")
```
###Testing Accuracy of glm() model
```{r}
table(testDatav2$DefaultedLoans, as.numeric(testDatav2$prediction >= 0.5))
```
### Accuracy
```{r}
(868+8190)/nrow(testDatav2)
(7849+2953)/nrow(testDatav2)
```
### ROC Curve
```{r}
library(ROCR)
#roc_prediction = prediction(testDatav2$prediction, testDatav2$DefaultedLoans)as.numeric(performance(pred, "auc")@y.values)
# Make predictions on training set
train_pred = predict(simpleglmv2, type="response")
# Prediction function
ROCT_Prediction = prediction(train_pred, trainDatav2$DefaultedLoans)
# Performance function
ROCR_Performance = performance(ROCT_Prediction, "tpr", "fpr")
# Plot ROC curve
plot(ROCR_Performance)
# Add colors
plot(ROCR_Performance, colorize=TRUE)
# Add threshold labels
plot(ROCR_Performance, colorize=TRUE, print.cutoffs.at=seq(0,1,by=0.05), text.adj=c(-0.2,2.0))
```
## Vizualization of Ireland property price market
```{r}
## Load the library
library(dplyr)
library(maps)
library(reshape2)
library(leaflet)
library(ggplot2)
library(ggmap)
library(gridExtra)
library(htmlwidgets)
library(readr)
weatherIcon <- makeIcon(
iconUrl = "./fig/weather.png",
iconWidth = 30,
iconHeight = 30
)
popupInfo <- paste(testDatav2[['ContractRef']],
", ",
testDatav2[['LoanBalance']],
"<br>",
"Has Defaulted?: ",
testDatav2[['DefaultedLoans']],
"<br>",
"Credit Rating is:: ",
testDatav2[['CreditRating']],
"<br>",
"LTV: ",
testDatav2[['LTV']],
"<br>",
"Property Value: ",
testDatav2[['PropertyValue']],
sep='')
MapDisplay <- leaflet(testDatav2) %>%
setView(-6.24420, 53.30867, zoom = 12) %>%
addTiles() %>%
addMarkers(testDatav2$AddressLongitude, testDatav2$AddressLatitude, popup= ~ popupInfo,
options = popupOptions(closeButton = TRUE),
clusterOptions = markerClusterOptions(),
icon = weatherIcon)
MapDisplay
saveWidget(MapDisplay, file="MapDisplayv2.html")
```
####################################
#
#Update this part
#
#####################################
```{r}
library(lubridate)
library(ggplot2)
library(dplyr)
library(stringr)
library(caret)
library(rpart)
library(rattle)
library(ROSE)
library(ROCR)
library(MASS)
library(ipred)
library(plyr)
library(rpart.plot)
library(readr)
levels.default(trainDatav2$DefaultedLoans)
table(trainDatav2$DefaultedLoans, trainDatav2$CreditRating)
ggplot(trainDatav2, aes(x = trainDatav2$LoanBalance)) +geom_histogram(aes(fill = CreditRating)) +facet_wrap(~DefaultedLoans, ncol=1)
```
```{r}
#Decision Tree
mydata.rpart.0 <- rpart(DefaultedLoans ~ ., data = trainDatav2)
mydata.rpart.1 <- rpart(DefaultedLoans ~ . , data = testDatav2,
control=rpart.control(minsplit=10, minbucket = 3, cp=0.0006))
fancyRpartPlot(mydata.rpart.1)
```
```{r}
predictions.1 <- (predict(mydata.rpart.1, testDatav2, type = "class"))
confusionMatrix(predictions.1, testDatav2$DefaultedLoans)
```
#Model for Tableau
```{r}
lrmodel <- glm(DefaultedLoans ~ CreditRating + LoanBalance + PropertyValue, data = trainDatav2, family = "binomial");
save(lrmodel, file = "Model/lrmodelv2.rda")
```
```{r}
load("Model/lrmodelv2.rda")
prob <- predict(lrmodel, newdata = testDatav2, type = "response")
plot(prob,testDatav2$CreditRating)
```
#Decision Tree
##Decision Tree Model
```{r}
#Decision Tree for Tableu
library(rpart)
library(rattle) # Fancy tree plot
library(rpart.plot) # Enhanced tree plots
library(RColorBrewer) # Color selection for fancy tree plot
library(party) # Alternative decision tree algorithm
library(partykit) # Convert rpart object to BinaryTree
library(caret)
library(tree)
defaultLoanTree <- rpart(DefaultedLoans ~ NewLoan + County + LoanBalance + PropertyValue + InterestIncome + CreditRating + AnnualPYMT + County + LTV + LTVCategory + InArrears + MortgageType + MortgageYears + AddressLatitude + AddressLongitude ,method = "class",data=trainDatav2, control = rpart.control(minisplit=5000,cp = 0.001))
save(fit, file = "Model/classificationTreeV2.rda")
print(defaultLoanTree)
prp(defaultLoanTree)
tree.1 <- defaultLoanTree
fancyRpartPlot(tree.1)
##################################
## Prunning Decision Tree using rpart()
#PruneTree = prune(fit, cp = 0.003)
#prp(PruneTree)
#fancyRpartPlot(PruneTree)
```
## Stats for Decision Tree
```{r}
printcp(defaultLoanTree)
```
## Confusion Matrix for traindata
```{r}
defaultPredict <- predict(defaultLoanTree, trainDatav2, type = 'class')
matrix <- table(defaultPredict, trainDatav2$DefaultedLoans)
print(matrix)
print((matrix[4]+matrix[1])/nrow(trainDatav2))
```
## Confusion Matrix for test data
```{r}
defaultPredict <- predict(defaultLoanTree, testDatav2, type = 'class')
matrix <- table(defaultPredict, testDatav2$DefaultedLoans)
print(matrix)
print((matrix[4]+matrix[1])/nrow(testDatav2))
```
## Classification Tree Model (Small Tree)
```{r}
library(rpart)
library(rpart.plot) # Enhanced tree plots
library(RColorBrewer)
library(rattle) # Fancy tree plot) # Color selection for fancy tree plot
library(caret)
fit <- rpart(DefaultedLoans ~ NewLoan + County + LoanBalance +
PropertyValue + InterestIncome + CreditRating + AnnualPYMT +
County + LTV + LTVCategory + InArrears + MortgageType + MortgageYears +
AddressLatitude + AddressLongitude, data=testDatav2, control=rpart.control(minsplit =25,cp=0.002),method="class")
prp(fit)
fancyRpartPlot(fit)
```
## Decision Tree using party() package
```{r}
library(party)
library(partykit)
fit <- ctree(DefaultedLoans ~ NewLoan + County + LoanBalance +
PropertyValue + InterestIncome + CreditRating + AnnualPYMT +
County + LTV + LTVCategory + InArrears + MortgageType + MortgageYears +
AddressLatitude + AddressLongitude, data=testDatav2)
plot (fit, main="Conditional Inference Tree") # the ctreeprp(fit)
```
#Adding Prediction variable in Dataset of Decision Tree
```{r}
dt_data_model <-testDatav2
dt_data_model$PredictionDT <- predict(defaultLoanTree, testDatav2, type = 'class')
write.csv(dt_data_model, "Data/dt_data_model.csv")
```