-
Notifications
You must be signed in to change notification settings - Fork 1
/
sgd.go
73 lines (65 loc) · 1.45 KB
/
sgd.go
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
package main
import (
"math/rand"
)
// SGD support stochastic gradient decent through implementation of
// a random out-of-bag ChooseOne function
type SGD struct {
samples []int `slice holds samples yet to be chosen`
total int
refresh bool
pRNG *rand.Rand
}
func NewSGD(numsamples int, pRNG *rand.Rand) Descender {
sgd := &SGD{
total: numsamples,
pRNG: pRNG,
refresh: false,
}
sgd.refreshSamples()
sgd.refresh = false
return sgd
}
func (sgd *SGD) refreshSamples() {
sgd.refresh = true
sgd.samples = make([]int, sgd.total)
for idx := range sgd.samples {
sgd.samples[idx] = idx
}
}
// ChooseOne sample and remove from samples slice
// If the samples slice is spent, refresh
func (sgd *SGD) ChooseOne() int {
numsamples := len(sgd.samples)
idx := sgd.pRNG.Intn(numsamples)
choice := sgd.samples[idx]
switch numsamples {
case 1:
sgd.refreshSamples()
default:
sgd.samples = append(sgd.samples[:idx], sgd.samples[idx+1:]...)
}
return choice
}
func (sgd *SGD) ChooseMany(numBatches int) (batches [][]int) {
batches = make([][]int, numBatches)
for i := len(sgd.samples); i > 0; i-- {
batches[i%numBatches] = append(batches[i%numBatches], sgd.ChooseOne())
}
sgd.refreshSamples()
return batches
}
func (sgd *SGD) SampledAll() bool {
switch sgd.refresh {
case false:
return false
default:
sgd.refresh = false
return true
}
}
type Descender interface {
ChooseOne() int
ChooseMany(numBatches int) [][]int
SampledAll() bool
}