File: stochastic-gradient-maxLik.R

package info (click to toggle)
r-cran-maxlik 1.5-2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,676 kB
  • sloc: sh: 39; makefile: 2
file content (256 lines) | stat: -rw-r--r-- 8,607 bytes parent folder | download | duplicates (2)
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
### R code from vignette source 'stochastic-gradient-maxLik.Rnw'

###################################################
### code chunk number 1: foo
###################################################
options(keep.source = TRUE, width = 60,
        try.outFile=stdout()  # make try to produce error messages
        )
foo <- packageDescription("maxLik")


###################################################
### code chunk number 2: stochastic-gradient-maxLik.Rnw:163-164 (eval = FALSE)
###################################################
## maxSGA(fn, grad, start, nObs, control)


###################################################
### code chunk number 3: stochastic-gradient-maxLik.Rnw:375-379
###################################################
i <- which(names(MASS::Boston) == "medv")
X <- as.matrix(MASS::Boston[,-i])
X <- cbind("const"=1, X)  # add constant
y <- MASS::Boston[,i]


###################################################
### code chunk number 4: stochastic-gradient-maxLik.Rnw:384-385
###################################################
colMeans(X)


###################################################
### code chunk number 5: stochastic-gradient-maxLik.Rnw:392-393
###################################################
eigenvals <- eigen(crossprod(X))$values


###################################################
### code chunk number 6: stochastic-gradient-maxLik.Rnw:404-407
###################################################
betaX <- solve(crossprod(X)) %*% crossprod(X, y)
betaX <- drop(betaX)  # matrix to vector
betaX


###################################################
### code chunk number 7: stochastic-gradient-maxLik.Rnw:431-436
###################################################
gradloss <- function(theta, index)  {
   e <- y[index] - X[index,,drop=FALSE] %*% theta
   g <- t(e) %*% X[index,,drop=FALSE]
   2*g/length(index)
}


###################################################
### code chunk number 8: gradonly
###################################################
library(maxLik)
set.seed(3)
start <- setNames(rnorm(ncol(X), sd=0.1), colnames(X))
                           # add names for better reference
res <- try(maxSGA(grad=gradloss,
           start=start,
           nObs=nrow(X),
           control=list(iterlim=1000)
           )
    )


###################################################
### code chunk number 9: stochastic-gradient-maxLik.Rnw:476-483
###################################################
res <- maxSGA(grad=gradloss,
              start=start,
              nObs=nrow(X),
              control=list(iterlim=1000,
                           SG_clip=1e4)  # limit ||g|| <= 100
              )
summary(res)


###################################################
### code chunk number 10: stochastic-gradient-maxLik.Rnw:495-499
###################################################
loss <- function(theta, index) {
   e <- y[index] - X[index,] %*% theta
   -crossprod(e)/length(index)
}


###################################################
### code chunk number 11: stochastic-gradient-maxLik.Rnw:514-538
###################################################
res <- maxSGA(loss, gradloss,
              start=start,
              nObs=nrow(X),
              control=list(iterlim=1000,
                           # will misbehave with larger numbers
                           SG_clip=1e4,
                           SG_learningRate=0.001,
                           storeParameters=TRUE,
                           storeValues=TRUE
                           )  
              )
par <- storedParameters(res)
val <- storedValues(res)
par(mfrow=c(1,2))
plot(par[,1], par[,2], type="b", pch=".",
     xlab=names(start)[1], ylab=names(start)[2], main="Parameters")
## add some arrows to see which way the parameters move
iB <- c(40, nrow(par)/2, nrow(par))
iA <- iB - 10
arrows(par[iA,1], par[iA,2], par[iB,1], par[iB,2], length=0.1)
##
plot(seq(length=length(val))-1, -val, type="l",
     xlab="epoch", ylab="MSE", main="Loss",
     log="y")


###################################################
### code chunk number 12: stochastic-gradient-maxLik.Rnw:565-570
###################################################
i <- sample(nrow(X), 0.8*nrow(X))  # training indices, 80% of data
Xt <- X[i,]  # training data
yt <- y[i]
Xv <- X[-i,]  # validation data
yv <- y[-i]


###################################################
### code chunk number 13: stochastic-gradient-maxLik.Rnw:575-584
###################################################
gradloss <- function(theta, index)  {
   e <- yt[index] - Xt[index,,drop=FALSE] %*% theta
   g <- -2*t(e) %*% Xt[index,,drop=FALSE]
   -g/length(index)
}
loss <- function(theta, index) {
   e <- yv - Xv %*% theta
   -crossprod(e)/length(yv)
}


###################################################
### code chunk number 14: batch1
###################################################
res <- maxSGA(loss, gradloss,
              start=start,
              nObs=nrow(Xt),  # note: only training data now
              control=list(iterlim=100,
                           SG_batchSize=1,
                           SG_learningRate=1e-5,
                           SG_clip=1e4,
                           storeParameters=TRUE,
                           storeValues=TRUE
                           )  
              )
par <- storedParameters(res)
val <- storedValues(res)
par(mfrow=c(1,2))
plot(par[,1], par[,2], type="b", pch=".",
     xlab=names(start)[1], ylab=names(start)[2], main="Parameters")
iB <- c(40, nrow(par)/2, nrow(par))
iA <- iB - 1
arrows(par[iA,1], par[iA,2], par[iB,1], par[iB,2], length=0.1)
plot(seq(length=length(val))-1, -val, type="l",
     xlab="epoch", ylab="MSE", main="Loss",
     log="y")


###################################################
### code chunk number 15: momentum
###################################################
res <- maxSGA(loss, gradloss,
              start=start,
              nObs=nrow(Xt),
              control=list(iterlim=100,
                           SG_batchSize=1,
                           SG_learningRate=1e-6,
                           SG_clip=1e4,
                           SGA_momentum = 0.99,
                           storeParameters=TRUE,
                           storeValues=TRUE
                           )  
              )
par <- storedParameters(res)
val <- storedValues(res)
par(mfrow=c(1,2))
plot(par[,1], par[,2], type="b", pch=".",
     xlab=names(start)[1], ylab=names(start)[2], main="Parameters")
iB <- c(40, nrow(par)/2, nrow(par))
iA <- iB - 1
arrows(par[iA,1], par[iA,2], par[iB,1], par[iB,2], length=0.1)
plot(seq(length=length(val))-1, -val, type="l",
     xlab="epoch", ylab="MSE", main="Loss",
     log="y")


###################################################
### code chunk number 16: Adam
###################################################
res <- maxAdam(loss, gradloss,
              start=start,
              nObs=nrow(Xt),
              control=list(iterlim=100,
                           SG_batchSize=1,
                           SG_learningRate=1e-6,
                           SG_clip=1e4,
                           storeParameters=TRUE,
                           storeValues=TRUE
                           )  
              )
par <- storedParameters(res)
val <- storedValues(res)
par(mfrow=c(1,2))
plot(par[,1], par[,2], type="b", pch=".",
     xlab=names(start)[1], ylab=names(start)[2], main="Parameters")
iB <- c(40, nrow(par)/2, nrow(par))
iA <- iB - 1
arrows(par[iA,1], par[iA,2], par[iB,1], par[iB,2], length=0.1)
plot(seq(length=length(val))-1, -val, type="l",
     xlab="epoch", ylab="MSE", main="Loss",
     log="y")


###################################################
### code chunk number 17: SANN
###################################################
val <- NULL
# loop over batch sizes
for(B in c(1,10,100)) {
   res <- maxAdam(loss, gradloss,
                  start=start,
                  nObs=nrow(Xt),
                  control=list(iterlim=200,
                               SG_batchSize=1,
                               SG_learningRate=1e-6,
                               SG_clip=1e4,
                               SG_patience=5,
                           # worse value allowed only 5 times
                               storeValues=TRUE
                               )  
                  )
   cat("Batch size", B, ",", nIter(res),
       "epochs, function value", maxValue(res), "\n")
   val <- c(val, na.omit(storedValues(res)))
   start <- coef(res)
}
plot(seq(length=length(val))-1, -val, type="l",
     xlab="epoch", ylab="MSE", main="Loss",
     log="y")
summary(res)