-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstroke_prediction_app.Rmd
executable file
·365 lines (277 loc) · 6.3 KB
/
stroke_prediction_app.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
---
title: "Stroke"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
logo: img_heart/1.jpg
theme: united
source_code: embed
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
```
-----------------------------------------------------------------------
```{r global, include = FALSE}
library(glmnet)
library(PerformanceAnalytics)
library(tidymodels)
library(shiny)
library(vip)
library(readr)
library(skimr)
library(DT)
library(wesanderson)
library(shinyWidgets)
heart <- read.csv("stroke copy.csv") %>%
mutate_if(is.character, as.factor) %>% as.tibble()
# For figure color scheme
hotel.palette <- wes_palette("GrandBudapest2")
```
Sidebar {.sidebar}
===========================================================
`r h3("Objective:")`
`r h3("Predict who have high risk of a stroke.")`
<br>
- - -
<br>
```{r}
fileInput("file1","Choose a CSV file")
```
```{r}
numericRangeInput(inputId = "age",
label = "Age Range Input:",
value = c(min(heart$age), max(heart$age)))
```
```{r}
sliderInput(
inputId = "training_slider",
label = h4("Training Data Proportion"),
min = 0.10,
max = 0.90,
value = 0.75,
step = 0.05,
ticks = FALSE
)
```
```{r data.filtered}
heart_filtered <- reactive({
heart %>%
filter(age %>% between(left = input$age[1],
right = input$age[2]))
})
```
### Predictors:
1. Gender
2. Age
3. Hypertention
4. Heart disease
5. Ever married
6. Work type
7. Residence type
8. Glucose level
9. BMI
10. Smoking status
### Outcome:
Stroke(Yes/No)
```{r data.splitting}
# Data splitting and resampling
set.seed(123)
splits <- reactive({
initial_split(heart_filtered(),
strata = stroke,
prop = input$training_slider)
})
heart_other <- reactive({
training(splits())
})
heart_test <- reactive({
testing(splits())
})
# Create a validation set
set.seed(234)
prop.validation <- .20
val_set <- reactive({
validation_split(heart_other(),
strata = stroke,
prop = 1 - prop.validation)
})
```
```{r create.model}
lr_mod <-
logistic_reg(mixture = 1, penalty = tune()) %>%
set_engine("glmnet")
```
```{r create.recipe}
lr_recipe <- reactive({
recipe(stroke ~ ., data = heart_other()) %>%
step_dummy(all_nominal(),-all_outcomes()) %>%
step_zv(all_predictors()) %>%
step_normalize(all_predictors())
})
```
```{r create.workflow}
lr_workflow <- reactive({
workflow() %>%
add_model(lr_mod) %>%
add_recipe(lr_recipe())
})
```
```{r tuning.grid}
lr_reg_grid <-
tibble(penalty = 10 ^ seq(-4,-1, length.out = 10))
# Train and tune the model
lr_tune <- reactive({
lr_workflow() %>%
tune_grid(
resamples = val_set(),
#rset object
grid = lr_reg_grid,
control = control_grid(save_pred = TRUE),
#needed to get data for ROC curve
metrics = metric_set(roc_auc)
)
})
lr_best <- reactive({
lr_tune() %>%
select_best("roc_auc")
})
```
```{r best.workflow}
# Add best validation model to workflow
lr_workflow_best <- reactive({
finalize_workflow(lr_workflow(),
lr_best()) #needs to have the same column name as tune()
})
```
```{r fit.training}
# Inspect fit on entire training data
lr_fit <- reactive({
lr_workflow_best() %>%
fit(heart_other())
})
```
```{r last.fit}
lr_last_fit <- reactive({
last_fit(lr_workflow_best(),
splits())
})
```
```{r confusion.matrix}
lr_conf_mat <- reactive({
lr_last_fit() %>%
collect_predictions() %>%
conf_mat(truth = stroke, estimate = .pred_class)
})
```
**Correlation matrix chart**
=================================================================
```{r}
select(heart, -c("id")) %>%
keep(is.numeric) %>%
chart.Correlation(heart[, 2:3],
histogram = TRUE,
method = c("pearson"))
```
**Data summary**
=================================================================
```{r}
skim(heart)
```
**Validation Summary**
===========================================================
## Column {data-width="500"}
### Data Splitting
**Total Observations:**
`r reactive(dim(heart_filtered())[1] %>% scales::comma())`
**Training Set:**
`r reactive(dim(heart_other())[1] %>% scales::comma())`
**Validation Set:**
`r reactive((dim(heart_other())[1] * prop.validation) %>% scales::comma())`
**Testing Set:**
`r reactive(dim(heart_test())[1] %>% scales::comma())`
### Data Viewer
```{r}
heart %>%
slice(1:100) %>%
datatable(
options = list(
searching = FALSE,
pageLength = 50,
lengthMenu = c(50, 100)
),
style = "default"
)
```
## Column {data-width="500"}
### Case Imbalance Check
```{r}
output$case_plot <- renderPlot({
lr_recipe() %>%
prep() %>%
juice() %>%
ggplot(aes(stroke)) +
geom_bar(fill = wes_palette("BottleRocket1")[3]) +
theme_light()
})
plotOutput(outputId = "case_plot")
```
### Workflow
```{r}
# Report workflow with optimized `penalty`
renderPrint(lr_workflow_best())
```
**Classification Results**
===========================================================
## Column {data-width="500"}
### ROC
```{r}
output$lr_auc <- renderPlot({
lr_tune() %>%
collect_predictions(parameters = lr_best()) %>%
roc_curve(stroke, .pred_Yes) %>%
ggplot(aes(x = 1 - specificity, y = sensitivity)) +
geom_path(color = hotel.palette[4]) +
geom_abline(lty = 3, color = hotel.palette[4]) +
coord_equal() +
theme_classic()
})
plotOutput(outputId = "lr_auc")
```
### Confusion Matrix
```{r}
# renderPrint(lr_conf_mat() %>% tidy())
output$conf_mat_plot <- renderPlot({
lr_conf_mat() %>%
autoplot(type = "heatmap")
})
plotOutput(outputId = "conf_mat_plot")
```
## Column {data-width="500"}
### Variable Importance Plot
```{r, vip.plot}
output$vip_plot <- renderPlot({
lr_fit() %>%
pull_workflow_fit() %>%
vip(
num_features = 20,
aesthetics = list(
color = wes_palette("BottleRocket1")[3],
fill = wes_palette("BottleRocket1")[3],
size = 0.3
)
) +
theme_light()
})
plotOutput(outputId = "vip_plot")
```
### Prediction Metrics
```{r}
output$metrics <- renderTable({
lr_conf_mat() %>%
summary() %>%
select(-.estimator)
})
tableOutput(outputId = "metrics")
```