forked from pietrofranceschi/Physalia_ML
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3.training_testing.Rmd
More file actions
275 lines (207 loc) · 7.46 KB
/
3.training_testing.Rmd
File metadata and controls
275 lines (207 loc) · 7.46 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
---
title: "training and test sets"
author: "Filippo Biscarini"
date: "7/6/2021"
output: html_document
---
```{r setup, include=FALSE}
library("broom")
library("knitr")
library("ggplot2")
library("corrplot")
library("reshape2")
library("tidyverse")
library("tidymodels")
library("data.table")
knitr::opts_chunk$set(echo = TRUE)
```
## Reading the data
For this practical session on linear regression we are using a dataset on the relationship between the age of wild bats and DNA methylation at specific CpG sites ([data](https://datadryad.org/stash/dataset/doi:10.5061/dryad.rn0198d); [paper](https://onlinelibrary.wiley.com/doi/abs/10.1111/1755-0998.12925)).
The public dataset downloaded from Dryad is an `.xlsm` file, and can be read into *R* using the `read.xlsx()` function from the **xlsx** package.
```{r label="reading_data"}
ch4 <- readxl::read_excel("../data/DNA methylation data.xlsm")
ch4 <- na.omit(ch4[,-c(1,3)])
head(ch4)
```
## Training and testing sets
We now need to subset the data into a **training set** and a **testing set** We can randomly assign records from the original dataset to the two subsets, for instance $80\%$ to the training set and $20\%$ to the test set:
```{r pressure, echo=FALSE}
# set.seed(295)
n = nrow(ch4) ## sample size
n_training = round(0.8*n,0)
n_test = n - n_training
training_records <- sample(n,n_training)
training_set <- ch4[training_records,]
test_set <- ch4[-training_records,]
```
```{r}
## sanity checks
nrow(training_set)
nrow(test_set)
```
## Fitting the multiple linear regression model
Note: we use only the **training data** to fit the model!
```{r}
fit <- lm(Age ~ ., data = training_set)
tidy(fit)
r_squared <- summary(fit)$r.squared
print(paste("
cbind.data.framR^2", round(r_squared,4)))
```
The coefficient of determination $R^2$ is `r r_squared`
```{r}
data.frame("coefficient"=coef(fit))
```
[Question: How do we interpret the model coefficients?]{style="color:red"}
### The test error
```{r}
predictions <- predict(fit, newdata = test_set[,-1], interval="none", type = "response", na.action=na.pass)
cbind.data.frame("test_age"=test_set[,1], "predictions"=round(predictions,2))
```
```{r}
r_pearson = cor(test_set$Age,predictions)
r_spearman = cor(test_set$Age,predictions, method = "spearman")
mse = mean((test_set$Age-predictions)^2)
rmse = sqrt(mse)
nrmse = sqrt(mse)/mean(test_set$Age)
res.test = data.frame("metric"=c("MSE","RMSE","NRMSE","r pearson","r spearman"),
"value"=c(mse,rmse,nrmse,r_pearson,r_spearman))
res.test
```
```{r}
ggplot(data.frame("test_age"=test_set$Age,"predictions"=predictions), aes(x=predictions,y=test_age)) + geom_point()
```
### The training error
We can compare the test error measured above with the training error, i.e. the model performance measured on the training data:
```{r}
predictions <- predict(fit, newdata = training_set[,-1], interval="none", type = "response", na.action=na.pass)
```
```{r}
r_pearson = cor(training_set$Age,predictions)
r_spearman = cor(training_set$Age,predictions, method = "spearman")
mse = mean((training_set$Age-predictions)^2)
rmse = sqrt(mse)
nrmse = sqrt(mse)/mean(training_set$Age)
res.train = data.frame("metric"=c("MSE","RMSE","NRMSE","r pearson","r spearman"),
"value"=c(mse,rmse,nrmse,r_pearson,r_spearman))
res.train
```
```{r}
ggplot(data.frame("training_y"=training_set$Age,"predictions"=predictions), aes(x=predictions,y=training_y)) + geom_point()
```
```{r}
res.train |> inner_join(res.test, by = "metric") |> rename(training = value.x, test = value.y) |>
mutate(tst_trn_pct = round(100*(test-training)/training, 3))
```
## Exercise 3.1
- try a different training/testing split
- train the model
- measure the performance of the model
#### 1. split the data
```{r}
## write your code here
```
#### 2. train the model
```{r}
## write your code here
```
#### 3. evaluate the model on the test data
```{r}
## write your code here
```
## Validation set approach
We now implement the validation set approach. First, we choose the relative proportions for the training and test sets, e.g. $70\%$ and $30\%$. We feed the original dataset and the chose proportions in a function to implement the validation set approach for our regression problem, and then we repeat this 20 times, to get an estimate of the variability of the predictor $\hat{f}(x)$.
```{r validation_set, echo=FALSE}
validation_approach <- function(dataset,proportion) {
## prepare the subsets
n = nrow(dataset) ## sample size
n_training = round(proportion*n,0)
n_test = n - n_training
training_records <- sample(n,n_training)
training_set <- ch4[training_records,]
test_set <- ch4[-training_records,]
##fit the model
fit <- lm(Age ~ ., data = training_set)
## evaluate the model
predictions <- predict(fit, newdata = test_set[,-1], interval="none", type = "response", na.action=na.pass)
r_pearson = cor(test_set$Age,predictions)
r_spearman = cor(test_set$Age,predictions, method = "spearman")
mse = mean((test_set$Age-predictions)^2)
rmse = sqrt(mse)
nrmse = sqrt(mse)/mean(test_set$Age)
# res <- data.frame("metric"=c("MSE","RMSE","NRMSE","r pearson","r spearman"),
# "value"=c(mse,rmse,nrmse,r_pearson,r_spearman))
res <- data.frame(
"value"=c(mse,rmse,nrmse,r_pearson,r_spearman))
return(res)
}
n_replicates = 20
results <- replicate(n=n_replicates, validation_approach(ch4,0.7),simplify = FALSE)
df <- do.call(cbind.data.frame, results)
df <- transpose(df)
names(df) <- c("MSE","RMSE","NRMSE","r pearson","r spearman")
head(df,10)
```
We can now summarise and visualise the results:
```{r}
mDF <- reshape2::melt(df, variable.name = "metric")
mDF %>%
group_by(metric) %>%
summarise(N=n(), avg=mean(value), std=sd(value))
```
```{r}
p <- ggplot(mDF, aes(x = factor(1), y = value))
p <- p + geom_jitter(aes(colour=metric))
p <- p + facet_wrap(~metric, scales = "free")
p <- p + xlab("")
p
```
## k-fold cross-validation
Now, we implement 5-fold cross-validation. We set k=5 and then assign each observation from the original dataset to a fold:
```{r}
n = nrow(ch4)
k = 5
folds <- sample(x = seq(1,k), size = n, replace = TRUE)
table(folds)
```
We now fit and evaluate the model *k* times, and save results:
```{r}
cv.error = data.frame("fold"=NULL,"MSE"=NULL,"RMSE"=NULL,
"NRMSE"=NULL,"r_pearson"=NULL,"r_spearman"=NULL)
for(i in 1:k) {
print(paste("using validation fold",i))
training_set <- ch4[folds!=i,]
fit <- lm(Age ~ ., data = training_set)
test_set <- ch4[folds==i,]
predictions <- predict(fit, newdata = test_set[,-1], interval="none", type = "response", na.action=na.pass)
r_pearson = cor(test_set$Age,predictions)
r_spearman = cor(test_set$Age,predictions, method = "spearman")
mse = mean((test_set$Age-predictions)^2)
rmse = sqrt(mse)
nrmse = sqrt(mse)/mean(test_set$Age)
res = data.frame("fold"=i,"MSE"=mse,"RMSE"=rmse,
"NRMSE"=nrmse,"r_pearson"=r_pearson,"r_spearman"=r_spearman)
cv.error <- rbind.data.frame(cv.error,res)
}
```
```{r}
print(cv.error)
```
```{r}
mCV <- reshape2::melt(cv.error, id.vars = "fold", variable.name = "metric")
mCV %>%
group_by(metric) %>%
summarise(N=n(),avg = mean(value), std = sd(value))
```
```{r}
p <- ggplot(mCV, aes(x = factor(1), y = value))
p <- p + geom_jitter(aes(colour=metric))
p <- p + facet_wrap(~metric, scales = "free")
p <- p + xlab("")
p
```
## Exercise 3.2
- implement cross-validation with a different value for k (e.g. k=4, k=10, etc.): what happens to the estimated accuracy?
```{r}
## write your code here
```