-
Notifications
You must be signed in to change notification settings - Fork 63
/
FeatureEng_GermanCredit_Template.Rmd
98 lines (77 loc) · 2.05 KB
/
FeatureEng_GermanCredit_Template.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
---
title: "Feature Engineering German Credit - Baseline Attempt"
output:
html_document:
toc: yes
toc_float: yes
code_folding: hide
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
library(dplyr)
library(caret)
library(rpart)
library(rpart.plot)
```
# Load Data
```{r}
data(GermanCredit, package = "caret")
df = GermanCredit
df$Class = as.character(df$Class)
df$Class[df$Class == "Bad"] = "NotGood" # Rename, just for personal preference.
df$Class = as.factor(df$Class)
str(df)
head(df)
table(df$Class)
formula = Class ~ .
positive = "Good"
```
# Feature Engineering
```{r}
# Hint: use the preProcess() and predict() fkunctions
#p1 <- preProcess(...)
#df = predict(p1, df)
```
# Feature Selection
```{r}
dim(df)
set.seed(10)
# The following snippet will perform feature selection using caret's SBF = Selection By Filtering
#filterCtrl <- sbfControl(functions = rfSBF, number=1, verbose=T)
#r <- sbf(formula, data = df, sbfControl = filterCtrl)
#r
#df = cbind(df[,predictors(r)], Class=df$Class)]
#dim(df)
```
# Splitting the Data
```{r}
set.seed(123) # Set the seed to make it reproducible
train.index <- createDataPartition(df$Class, p = .8, list = FALSE)
train <- df[ train.index,]
test <- df[-train.index,]
# Double check that the stratefied sampling worked
table(df$Class)/nrow(df)
table(train$Class)/nrow(train)
table(test$Class)/nrow(test)
actual = test$Class
```
# Parameter Tuning - KNN
```{r}
grid <- expand.grid(.kmax = c(5),
.distance=c(1),
.kernel=c("rectangular"))
ctrl <- trainControl(method = "repeatedcv",
number = 10, repeats = 5,
classProbs = TRUE, returnResamp = "all")
model_fit <- train(formula,
data = train,
method = "kknn",
metric="Accuracy",
trControl=ctrl, tuneGrid = grid)
summary(model_fit)
model_fit
pred = predict(model_fit, test)
caret::confusionMatrix(data=pred, reference=actual, positive=positive, dnn=c("Predicted", "Actual"))
```