-
Notifications
You must be signed in to change notification settings - Fork 0
/
Simulation_examples.Rmd
449 lines (336 loc) · 10.7 KB
/
Simulation_examples.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
---
title: "Simulations"
output: github_document
---
## SDG vs. Adam:
see https://medium.com/mdr-inc/from-sgd-to-adam-c9fce513c4bb
SGD challenges:
- sparse data set where some features are frequently occurring and others are rare -> opting for a same learning rate for all the parameters will not be a good idea. We would want to make a larger update for the rarely occurring ones as compared to the frequently occurring features
- challenge: choosing a proper learning rate. Very large learning rate: dwindle around the minimum, very small learning rate: the convergence gets really slow.
- In the neural networks domain one of the issue we face with the highly non convex functions is that one gets trapped in the numerous local minimas
Adam:
- Adaptive Moment Estimation (Adam) is a good alternative to SGD
- inherits itself from Adagrad and RMSProp
Adagrad:
- works better for sparse data by adapting the learning rate to the parameters, bu having a low learning rate for the parameters associated to frequently occuring features and larger updates to the ones with infrequent features
- while SGD has a common learning rate for all param. Adagrad uses different learning rates for the parameters at every timestep.
- but learning rate becomes infinitesimally small.
RMSprop:
- alternative to Adagrad
-> Adam is a combination of both
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, dpi = 300)
library(hierNet)
library(reticulate)
use_python("usr/local/bin/python")
```
```{python echo = F}
#% import python modules
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch.utils.data import Dataset, DataLoader
```
```{python echo = F}
from torch.optim.lr_scheduler import StepLR
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import scale
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import pandas as pd
from sklearn.metrics import mean_squared_error as rmse
from numpy import genfromtxt
```
## 1. HierNet in the LassoNetR framework
```{python}
from torch.nn.parameter import Parameter
from torch.nn import functional as F
# %% Define HierNet
class torch_hiernet(torch.nn.Module):
# """
# 2-layer NN with RelU
# """
def __init__(self, D_in, D_out, H):
super().__init__()
self.D_in = D_in
self.D_out = D_out
#self.W = Parameter(torch.randn((D_in, D_in)))
self.W1 = torch.nn.Linear(D_in, D_in, bias = False)
return
def forward(self, x):
y = F.linear(x, self.W1.weight)
# sum over dim 1, insert dummy dimension
z = (x*y).sum(1)[:,None]
return z
```
```{r}
source("R/reticulate_setup.R")
source("R/LassoNetR.R")
```
```{r eval = F}
fit_all <- list()
D_in = 10L
D_out = 1L
batch_size = 5L
i = 0
for(N in c(50L, 200L, 500L)){
i = i + 1
X = matrix(rnorm(N * D_in), N, D_in)
y = 1 * X[, 1] + 2. * X[, 2] - 3*X[, 3] +
5*X[, 5] - 1.*X[, 1]*X[, 2] + 2*X[, 5]*X[,6]
H = N/10L
fit_all[[i]] <- LassoNetR(X = X, Y = y,
NN = py$torch_hiernet,
D_in = D_in, D_out = D_out, H = H,
batch_size=batch_size, lam = 5L, M = 1L,
n_epochs = 30L, valid = TRUE, optimizer = "SGD")
}
```
```{r eval = F, echo = F}
saveRDS(fit_all, "temp/fit_all.rds")
```
```{r echo = F}
fit_all <- readRDS("temp/fit_all.rds")
```
Training and validation loss comparison
```{r echo=F}
par(mfrow = c(1,3))
NN = c(50, 200, 500)
i = 0
for(fit in fit_all){
i = i + 1
range = c(unlist(fit$loss$train_loss), unlist(fit$loss$valid_loss))
{plot(unlist(fit$loss$train_loss), ylab = "Loss", xlab = "Epoch",
pch = 4, type = "b", #ylim = range(range),
ylim = c(0, 40),
main = paste0("N = ", NN[i] ,
", p = 10"))
points(unlist(fit$loss$valid_loss), col = "red", type = "b")
if(i == 1){
legend("topright", legend = c("Training", "Validation"), pch = c(4, 1),
col = c("black", "red"))
}
}
}
```
```{r eval = F}
fit_all_p <- list()
D_out = 1L
batch_size = 5L
N = 200L
H = 20L
i = 0
optim = c("SGD", "ADAM", "ADAM")
for(D_in in c(10L, 100L, 1000L)){
i = i + 1
## different alpha for different p
al0 = c(1e-3, 1e-4, 1e-5)
X = matrix(rnorm(N * D_in), N, D_in)
y = 1 * X[, 1] + 2. * X[, 2] - 3*X[, 3] +
5*X[, 5] - 1.*X[, 1]*X[, 2] + 2*X[, 5]*X[,6]
fit_all_p[[i]] <- LassoNetR(X = X, Y = y,
NN = py$torch_hiernet,
D_in = D_in, D_out = D_out, H = H,
batch_size=batch_size, lam = 5L, M = 1L,
n_epochs = 80L, valid = TRUE, optimizer = optim[i],
alpha0 = al0[i])
}
```
```{r eval = F, echo = F}
saveRDS(fit_all_p, "temp/fit_all_p.rds")
```
```{r echo = F}
fit_all_p <- readRDS("temp/fit_all_p.rds")
```
```{r echo=F}
par(mfrow = c(1, 3))
pp = c(10L, 100L, 1000L)
i = 0
for(fit in fit_all_p){
i = i + 1
range = c(unlist(fit$loss$train_loss), unlist(fit$loss$valid_loss))
{plot(unlist(fit$loss$train_loss), ylab = "Loss", xlab = "Epoch",
pch = 4, type = "b", #ylim = range(range),
ylim = c(0, 350),
main = paste0("N = 200",
", p = ", pp[i]))
points(unlist(fit$loss$valid_loss), col = "red", type = "b")
if(i == 1){
legend("topright", legend = c("Training", "Validation"), pch = c(4, 1),
col = c("black", "red"))
}
}
}
```
## 2. LassoNet with Feed Forward architecture
```{python}
from torch.nn.parameter import Parameter
from torch.nn import functional as F
class FeedForward(torch.nn.Module):
"""
2-layer NN with RelU
"""
def __init__(self, D_in, D_out, H):
super().__init__()
self.D_in = D_in
self.D_out = D_out
self.W1 = torch.nn.Linear(D_in, H, bias=True)
self.relu = torch.nn.ReLU()
self.W2 = torch.nn.Linear(H, H)
self.W3 = torch.nn.Linear(H, D_out)
return
def forward(self, x):
x = self.W1(x)
x = self.relu(x)
x = self.W2(x)
x = self.relu(x)
x = self.W3(x)
return x
```
```{r eval = F}
fit_allFF <- list()
D_in = 10L
D_out = 1L
batch_size = 5L
i = 0
for(N in c(50L, 200L, 500L)){
i = i + 1
X = matrix(rnorm(N * D_in), N, D_in)
y = 1 * X[, 1] + 2. * X[, 2] - 3*X[, 3] +
5*X[, 5] - 1.*X[, 1]*X[, 2] + 2*X[, 5]*X[,6]
H = N/10L
class(H) <- "integer"
fit_allFF[[i]] <- LassoNetR(X = X, Y = y,
NN = py$FeedForward,
D_in = D_in, D_out = D_out, H = H,
batch_size=batch_size, lam = 5L, M = 1L,
n_epochs = 30L, valid = TRUE, optimizer = "SGD")
}
```
```{r eval = F, echo = F}
saveRDS(fit_allFF, "temp/fit_allFF.rds")
```
```{r echo = F}
fit_allFF <- readRDS("temp/fit_allFF.rds")
```
Training and validation loss comparison
```{r echo=F}
par(mfrow = c(1,3))
NN = c(50, 200, 500)
i = 0
for(fit in fit_allFF){
i = i + 1
range = c(unlist(fit$loss$train_loss), unlist(fit$loss$valid_loss))
{plot(unlist(fit$loss$train_loss), ylab = "Loss", xlab = "Epoch",
pch = 4, type = "b", #ylim = range(range),
ylim = c(0, 50),
main = paste0("N = ", NN[i] ,
", p = 10"))
points(unlist(fit$loss$valid_loss), col = "red", type = "b")
if(i == 1){
legend("topright", legend = c("Training", "Validation"), pch = c(4, 1),
col = c("black", "red"))
}
}
}
```
```{r eval = F}
fit_allFF_p <- list()
D_out = 1L
batch_size = 20L
N = 200L
#H = 20L
i = 0
optim = c("SGD", "ADAM", "ADAM")
for(D_in in c(10L, 100L, 1000L)){
i = i + 1
## different alpha for different p
al0 = c(1e-3, 1e-4, 1e-5)
X = matrix(rnorm(N * D_in), N, D_in)
y = 1 * X[, 1] + 2. * X[, 2] - 3*X[, 3] +
5*X[, 5] - 1.*X[, 1]*X[, 2] + 2*X[, 5]*X[,6]
fit_allFF_p[[i]] <- LassoNetR(X = X, Y = y,
NN = py$torch_hiernet,
D_in = D_in, D_out = D_out, H = D_in,
batch_size=batch_size, lam = 5L, M = 1L,
n_epochs = 80L, valid = TRUE, optimizer = optim[i],
alpha0 = al0[i])
}
```
```{r eval = F, echo = F}
saveRDS(fit_allFF_p, "temp/fit_allFF_p.rds")
```
```{r echo = F}
fit_allFF_p <- readRDS("temp/fit_allFF_p.rds")
```
```{r echo=F}
par(mfrow = c(1, 3))
pp = c(10L, 100L, 1000L)
i = 0
for(fit in fit_allFF_p){
i = i + 1
range = c(unlist(fit$loss$train_loss), unlist(fit$loss$valid_loss))
{plot(unlist(fit$loss$train_loss), ylab = "Loss", xlab = "Epoch",
pch = 4, type = "b", #ylim = range(range),
ylim = c(0, 450),
main = paste0("N = 200",
", p = ", pp[i]))
points(unlist(fit$loss$valid_loss), col = "red", type = "b")
if(i == 1){
legend("topright", legend = c("Training", "Validation"), pch = c(4, 1),
col = c("black", "red"))
}
}
}
```
### Does the validation loss get better for larger M (M = 500)?
```{r eval = F}
fit_allFF_pM <- list()
D_out = 1L
batch_size = 20L
N = 200L
#H = 20L
i = 0
optim = c("SGD", "ADAM", "ADAM")
for(D_in in c(10L, 100L, 1000L)){
i = i + 1
## different alpha for different p
al0 = c(1e-3, 1e-4, 1e-5)
X = matrix(rnorm(N * D_in), N, D_in)
y = 1 * X[, 1] + 2. * X[, 2] - 3*X[, 3] +
5*X[, 5] - 1.*X[, 1]*X[, 2] + 2*X[, 5]*X[,6]
fit_allFF_pM[[i]] <- LassoNetR(X = X, Y = y,
NN = py$torch_hiernet,
D_in = D_in, D_out = D_out, H = D_in,
batch_size=batch_size, lam = 5L, M = 500L,
n_epochs = 80L, valid = TRUE, optimizer = optim[i],
alpha0 = al0[i])
}
```
```{r eval = F, echo = F}
saveRDS(fit_allFF_pM, "temp/fit_allFF_pM.rds")
```
```{r echo = F}
fit_allFF_pM <- readRDS("temp/fit_allFF_pM.rds")
```
```{r echo=F}
par(mfrow = c(1, 3))
pp = c(10L, 100L, 1000L)
i = 0
for(fit in fit_allFF_pM){
i = i + 1
range = c(unlist(fit$loss$train_loss), unlist(fit$loss$valid_loss))
{plot(unlist(fit$loss$train_loss), ylab = "Loss", xlab = "Epoch",
pch = 4, type = "b", #ylim = range(range),
ylim = c(0, 400),
main = paste0("N = 200",
", p = ", pp[i]))
points(unlist(fit$loss$valid_loss), col = "red", type = "b")
if(i == 1){
legend("topright", legend = c("Training", "Validation"), pch = c(4, 1),
col = c("black", "red"))
}
}
}
```
It does get better for $p=100$ and worse for $p=1000$...