Repository navigation
Expand file tree
/
Copy pathneuralnet_implementation_sol.Rmd
More file actions
323 lines (239 loc) · 12.4 KB
/
Copy pathneuralnet_implementation_sol.Rmd
File metadata and controls
323 lines (239 loc) · 12.4 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
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
---
output:
html_document:
df_print: paged
output: default
title: "Implementing a Neural Network"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Neural network for longitudinal data
The aim of this notebook is to predict 5 years mortality for patients diagnosed with hypertension before the age of 65 using on their disease history. To accomplish this task, we will use the synthetic data provided.
Here we load the libraries used for the data transformation, for the neural network implementation and for the analysis of the results. If a library is missing, you can install it using the command *install.packages(pkgs)*.
```{r, echo=TRUE, message=FALSE, results='hide'}
library(tidyverse)
library(lubridate)
library(pROC)
library(keras3)
```
Here you can load the three files used in this notebook. I would suggest to spend a few minutes here to understand the content of the different files. Use head to visualize the three tables. In order to make transformation to the dates, we need to parse them as such. Either load the tables parsing directly the columns as date or use the command *as.Date* to convert them in the desired format - check which columns should be dates. Note that lpr.tsv only contains hypertension disease codes.
```{r}
cpr <- read.csv('cpr.tsv', sep='\t', header = TRUE)
lpr <- read.csv('lpr.tsv', sep='\t', header = TRUE)
trj <- read.csv('trj.tsv', sep='\t', header = TRUE)
head (cpr)
head (lpr)
head (trj)
```
In order to make transformation to the dates, we need to parse them as such. The command *as.Date* is used to convert the columns in the desired format.
```{r}
cpr$BIRTHDAY <- as.Date(cpr$BIRTHDAY)
cpr$STATUS_DATE <- as.Date(cpr$STATUS_DATE)
lpr$ADM_DATE <- as.Date(lpr$ADM_DATE)
```
First we select the patients that got hypertension disease code before 65y. The age information is not included in the lpr table, so we need to merge lpr and cpr table. The function *inner_join* from *dplyr* library allows us to merge the two tables. The merging key is passed to the function through the parameter *by=*.
```{r}
cpr_to_lpr <- inner_join(cpr, lpr, by='ID')
```
Then we add the columns *AGE_AT_DIAG* and *AGE_AT_STATUS* using the mutate function in *dplyr.* The two columns indicate how old was the patient when he first got diagnosed with hypertension and how old he was at the *STATUS_DATE (date of death or censoring)*.
```{r}
cpr_to_lpr <- cpr_to_lpr %>%
mutate(
AGE_AT_DIAG = time_length(BIRTHDAY %--% ADM_DATE, "years") %>% round(1),
AGE_AT_STATUS = time_length(BIRTHDAY %--% STATUS_DATE, "years") %>% round(1)
)
head(cpr_to_lpr) %>% select(AGE_AT_DIAG, AGE_AT_STATUS)
```
At this point, we can filter out the patients that we do not want to include in the study. In this case, as arbitrary choice, we select only the patients who got diagnosed before 65. In addition to this, we will also exclude those patients that were alive at the 'end of the registry' and received their I10 diagnosis in the last 5 years. This choice allows us to simplify the design of the experiment by ignoring censored patients. Patients that were alive at STATUS_DATE have STATUS=1. Patients that have STATUS=90 died on their STATUS_DATE.
```{r}
cpr_to_lpr <- cpr_to_lpr %>%
filter(AGE_AT_DIAG < 65) %>%
filter((AGE_AT_STATUS - AGE_AT_DIAG) > 5 | STATUS == 90)
head(cpr_to_lpr)
```
The final step is to generate the outcome column. The binary outcome encodes death as 1 and survival as 0. You can use again the mutate function from *dplyr*.
```{r}
cpr_to_lpr <- cpr_to_lpr %>%
mutate (
OUTCOME = (AGE_AT_STATUS - AGE_AT_DIAG) < 5 & STATUS == 90 %>% as.integer() #Death needs to occur within 5 years, and LPR STATUS has to be 90.
)
head(cpr_to_lpr)
```
#### Generate the input
The model takes as input a table containing the target (the OUTCOME column generated above) and the input data. In order to generate the input for the model, we first need to extract the unique trajectories all the patients have, so that we can index them.
```{r}
unique_trj <- unique(trj[-1]) # with -1 we exclude the ID column (we would have otherwise a unique row for each patient)
unique_trj$TRJ_IDX <- paste("T", c(1:nrow(unique_trj)), sep='') # here we generate an index for each trajectory.
head(unique_trj)
```
Now we would like to add this trajectory index, contained in the table *unique_trj*, to the table loaded from *trj.tsv*. We accomplish this using again the function *inner_join*. Now the merging keys are the four diseases constituting each trajectory.
```{r}
merged_trj <- inner_join(trj, unique_trj,
by = c("Disease1", "Disease2", "Disease3", "Disease4")) %>%
select("ID","TRJ_IDX") # Here we select only the column ID and TRJ_IDX, as the single disease information is not used in the model.
head(merged_trj)
```
Since the trajectory index is a categorical feature, we need to find a way to include this information in the input data. The choice here is to one hot encode it. Using one hot encoding, each column represents a unique trajectory, and a binary value encodes the presence/absence of that specific trajectory for the patient in that row.
```{r}
input_trj <- merged_trj %>%
unique() %>%
mutate(n = 1)%>%
spread(TRJ_IDX, n, fill = 0) %>%
filter(ID %in% cpr_to_lpr$ID)
head(input_trj)
```
Here we simply add the outcome column merging the *input_trj* file generated above and the *cpr_to_lpr* table.
```{r}
nn_input <- inner_join(input_trj, cpr_to_lpr %>% select(ID, OUTCOME), by="ID") # we select only ID and OUTCOME from cpr_to_lpr
```
When evaluating the perfomance of the model, we use an external dataset that has not been seen by the model during training. This set is called for this reason test set. In the following section we extract 70% of the IDs randomly, and then we use them for extracting the training set. The remaining IDs will populate the test set.
```{r}
train_id <- nn_input %>%
sample_frac(0.70) %>%
select(ID)
nn_input_train <- nn_input %>%
filter(ID %in% train_id$ID) %>%
select(- ID) # We exclude the ID column as we do not want it included in the input data
nn_input_test <- nn_input %>%
filter(!ID %in% train_id$ID) %>%
select(- ID) # We exclude the ID column as we do not want it included in the input data
```
### Define the model
We have talked about a few of the things to consider when creating neural networks. Try to play around a bit with the [Tensorflow Playground](https://playground.tensorflow.org/). The goal is to create a network that takes in the features X1, X2, etc. and attempts to correctly classify the orange and blue dots. To train the model press the play button and try to adjust the number of hidden layers and neurons in order to create a better model. You can see how well you are doing by whether the background color (classification boundary for the orange and blue class) matches the color of the dots. You have probably noticed that the number of hyperparameters to tune is high, resulting in combinations that can lead to different performances. Before trying to define a model yourself, I would suggest you to have a look at *?keras_model_sequential* documentation to have a full overview of the function. You can tune the parameters and try to achieve the best AUC value.
Try to use the keras package. Have a look at the documentation [here](https://www.rstudio.com/blog/keras-for-r/) and build the best possible neural network.
```{r}
## add code here
#see this example
model <- keras_model_sequential()
model %>%
layer_dense(units = 256, activation = "relu") %>%
# Dropout removes features at random during training with some rate.
# This reduces reliance on specific features and makes the network
# less prone to overfitting.
layer_dropout(rate = 0.4) %>%
layer_dense(units = 128, activation = "relu") %>%
layer_dropout(rate = 0.3) %>%
layer_dense(units = 1, activation = "sigmoid")
model %>% compile(
loss = "binary_crossentropy",
optimizer = optimizer_rmsprop(),
# metrics = c("accuracy", "mse")
)
xtrain_keras <- simplify2array(nn_input_train[!(colnames(nn_input_train) %in% "OUTCOME")])
ytrain_keras <- simplify2array(nn_input_train[colnames(nn_input_train) %in% "OUTCOME"])
history <- model %>% fit(
xtrain_keras, ytrain_keras,
epochs = 30, batch_size = 128,
validation_split = 0.2,
)
```
### Evaluation
Here we evaluate the network on the test set. First we use the compute function for generating the output (the compute function does not update the weights of the network, so the model does not train on the data passed). After that we can use the functions inside *pROC* to extract the metrics we need for the evaluation. You can also use the plot.roc function to visualize the roc curve.
```{r}
xtest_keras <- simplify2array(nn_input_test[!(colnames(nn_input_test) %in% "OUTCOME")])
ytest_keras <- simplify2array(nn_input_test[colnames(nn_input_test) %in% "OUTCOME"])
pred <- model %>% predict(xtest_keras)
roc_obj <- roc(as.factor(ytest_keras), as.vector(pred))
auc(roc_obj)
coords(roc_obj, c(0.1,0.2, 0.4, 0.5, 0.7), ret=c("tp", "tn", "fp", "fn", "sensitivity", "specificity"))
plot.roc(roc_obj)
```
## Additional
There are many ways that the input data can be modeled and these have different assumptions. The one hot encoding of trajectories, as we have done in this exercise is just one example. Instead you can try to one hot encode the ICD codes instead of the trajectories. Treat each row in the *trj* dataframe as a unique observation and predict hypertension as before using the ICD codes directly instead of the trajectories.
Here are a few things you can consider:
Instead of manually converting the codes to one hot encodings you can use *?layer_embedding* . This will change the dimensionality of your input and you will need to adjust the model to reflect that. *layer_max_pooling_1d* is one example.
Another suggestion is to model the temporal relation between diagnoses, as the order of diseases often play an important role in our understanding of the patient. Instead of using a pooling function the dependencies can be modeled using a sequential layer (*?layer_gru*).
```{r}
library(rsample)
# For simplicity we use the trj from before and use as individual observations with the labels defined previously.
df <- trj |>
left_join(
cpr_to_lpr |> select(ID, OUTCOME),
by = "ID"
) |>
filter(!is.na(OUTCOME))
X <- as.matrix(df |> select(starts_with("Disease")))
max_length <- 4L #Since there is 4 diagnoses per trajectory
# Assign each unique codes a number
code_levels <- unique(as.vector(X))
code_levels <- code_levels[!is.na(code_levels)]
# Apply that number to our input data
X <- matrix(
match(X, code_levels),
nrow = nrow(X),
ncol = ncol(X)
)
y <- as.integer(df$OUTCOME)
# A different way of splitting training and test
split <- initial_split(
data.frame(idx = seq_along(y), outcome = y),
prop = 0.8,
strata = outcome
)
train_idx <- training(split)$idx
test_idx <- testing(split)$idx
X_train <- X[train_idx, , drop = FALSE]
X_test <- X[test_idx, , drop = FALSE]
y_train <- y[train_idx]
y_test <- y[test_idx]
```
```{r}
# We define how our input looks
input <- keras_input(
shape = max_length,
dtype = "int32"
)
# A dense model that performs a max pooling operation
output <- input |>
layer_embedding(
input_dim = length(code_levels) + 1,
output_dim = 32,
mask_zero = TRUE
) |>
layer_dense(units = 64, activation = "relu") |>
layer_max_pooling_1d(pool_size = max_length) |>
layer_flatten() |>
layer_dense(units = 32, activation = "relu") |>
layer_dropout(0.2) |>
layer_dense(units = 1, activation = "sigmoid")
model_dense <- keras_model(input, output)
model_dense %>% compile(
loss = "binary_crossentropy",
optimizer = optimizer_rmsprop(),
# metrics = c("accuracy", "mse")
)
history <- model_dense %>% fit(
X_train, y_train,
epochs = 30, batch_size = 128,
validation_split = 0.2,
)
```
```{r}
input <- keras_input(
shape = max_length,
dtype = "int32"
)
# A sequential model that uses a gru
output <- input |>
layer_embedding(
input_dim = length(code_levels) + 1,
output_dim = 32,
mask_zero = TRUE
) |>
layer_gru(units = 64) |>
layer_dropout(0.2) |>
layer_dense(units = 32, activation = "relu") |>
layer_dense(units = 1, activation = "sigmoid")
model_gru <- keras_model(input, output)
model_gru %>% compile(
loss = "binary_crossentropy",
optimizer = optimizer_rmsprop(),
# metrics = c("accuracy", "mse")
)
history <- model_gru %>% fit(
X_train, y_train,
epochs = 30, batch_size = 128,
validation_split = 0.2,
)
```