-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtrain.R
More file actions
243 lines (154 loc) · 4.57 KB
/
train.R
File metadata and controls
243 lines (154 loc) · 4.57 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
# A sample model build using the financial audit dataset. We
# illustrate the model build and then save the model to file so that
# we can later load the model and use it to score new datasets.
suppressMessages(
{
library(tidyverse) # ggplot2, tibble, tidyr, readr, purr, dplyr
library(rpart)
library(magrittr) # Pipe operator %>% %<>% %T>% equals().
library(stringi) # String concat operator %s+%.
library(rattle)
library(stringr)
library(randomForest) # Impute missing values with na.roughfix()
})
# Name of the dataset.
dsname <- "audit"
# Identify the source location of the dataset.
dsloc <- "https://rattle.togaware.com"
# Construct the path to the dataset and display some if it.
dsname %s+% ".csv" %>%
file.path(dsloc, .) %T>%
cat("Dataset:", ., "\n") ->
dspath
# Ingest the dataset.
dspath %>%
read_csv() %T>%
glimpse() %>%
assign(dsname, ., .GlobalEnv)
# Prepare the dataset for usage with our template.
ds <- get(dsname)
# Review the variables to optionally normalise their names.
names(ds)
# Capture the original variable names for use later on.
onames <- names(ds)
# Normalise the variable names.
names(ds) %<>% normVarNames() %T>% print()
# Tune specific variable names: remove prefix.
if (TRUE)
{
names(ds) %>% str_detect("_") -> uvars
names(ds)[uvars] %<>% str_replace("^[^_]*_", '') %T>% print()
}
# Index the original variable names by the new names.
names(onames) <- names(ds)
# Confirm the results are as expected.
glimpse(ds)
# Review the first few observations.
head(ds) %>% print.data.frame()
# Review the last few observations.
tail(ds) %>% print.data.frame()
# Convert marital to a binary married.
ds %<>%
mutate(married=ifelse(marital=="Married", "yes", "no")) %>%
select(-marital)
# Convert occupation to just two groups.
labourers <- c("Cleaner", "Farming", "Machinist",
"Repair", "Service", "Transport")
ds %<>%
mutate(occupation=ifelse(occupation %in% labourers, "labourer", "office"))
# Convert education into two level
tertiary <- c("Associate", "Bachelor", "College", "Doctorate", "Master", "Professional")
ds %<>%
mutate(education=ifelse(education %in% tertiary, "tertiary", "secondary"))
# Review a random sample of observations.
sample_n(ds, size=6) %>% print.data.frame()
# Note the available variables.
ds %>%
names() %T>%
print() ->
vars
# Note the target variable.
target <- "adjusted"
# Place the target variable at the beginning of the vars.
c(target, vars) %>%
unique() %T>%
print() ->
vars
# Note the risk variable - measures the severity of the outcome.
risk <- "adjustment"
# Note any identifiers.
id <- c("id")
# Initialise ignored variables: identifiers and risk.
ignore <- union(id, if (exists("risk")) risk) %T>% print()
# Check the number of variables currently.
length(vars)
# Remove the variables to ignore.
vars <- setdiff(vars, ignore) %T>% print()
# Confirm they are now ignored.
length(vars)
# Convert all character to factor.
ds %>%
sapply(class) %>%
'=='("character") %>%
which() %>%
names() %T>%
print() ->
cvars
ds[cvars] %<>%
lapply(factor) %>%
data.frame() %>%
tbl_df()
# Count the number of missing values.
ds[vars] %>% is.na() %>% sum() %>% comcat()
# Impute missing values.
ds[vars] %<>% na.roughfix()
# Confirm that no missing values remain.
ds[vars] %>% is.na() %>% sum() %>% comcat()
# Record the number of observations.
nobs <- nrow(ds) %T>% comcat()
# Formula for modelling.
ds[vars] %>%
formula() %>%
print() ->
form
# Ensure the target is categoric.
class(ds[[target]])
ds[[target]] %<>% as.factor()
levels(ds[[target]]) <- c("no", "yes")
# Confirm the distribution.
ds[target] %>% table()
# Initialise random numbers for repeatable results.
seed <- 123
set.seed(seed)
# Partition the full dataset into three: train, validate, test.
nobs %>%
sample(0.70*nobs) %T>%
{length(.) %>% comcat()} %T>%
{head(.) %>% print()} ->
train
nobs %>%
seq_len() %>%
setdiff(train) %>%
sample(0.15*nobs) %T>%
{length(.) %>% comcat()} %T>%
{head(.) %>% print()} ->
validate
nobs %>%
seq_len() %>%
setdiff(union(train, validate)) %T>%
{length(.) %>% print()} %T>%
{head(.) %>% print()} ->
test
# Create a sample data.csv file for the demo from the test and
# validate datasets.
obs <- union(validate, test)
ds[obs,] %>% write_csv("data.csv")
# Note the class of the dataset.
class(ds)
# Build the model.
rp_control <- rpart.control(maxdepth=5)
m_rp <- rpart(form, data=ds, control=rp_control) %T>% print()
# Store model as generic variable.
model <- m_rp
# Save the model to file.
save(model, file="audit_rpart_model.RData")