forked from chewxy/lingo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.go
389 lines (331 loc) · 8.82 KB
/
train.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
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
package dep
import (
"fmt"
"os"
"sync"
"github.com/chewxy/lingo"
"github.com/chewxy/lingo/corpus"
"github.com/chewxy/lingo/treebank"
"github.com/pkg/errors"
)
// TrainerConsOpt is a construction option for trainer
type TrainerConsOpt func(t *Trainer)
// WithTrainingModel loads a trainer with a model
func WithTrainingModel(m *Model) TrainerConsOpt {
f := func(t *Trainer) {
t.Model = m
}
return f
}
// WithTrainingSet creates a trainer with a training set
func WithTrainingSet(st []treebank.SentenceTag) TrainerConsOpt {
f := func(t *Trainer) {
t.trainingSet = st
}
return f
}
// WithCrossValidationSet creates a trainer with a cross validation set
func WithCrossValidationSet(st []treebank.SentenceTag) TrainerConsOpt {
f := func(t *Trainer) {
t.crossValSet = st
}
return f
}
// WithConfig sets up a *Trainer with a NNConfig
func WithConfig(conf NNConfig) TrainerConsOpt {
f := func(t *Trainer) {
t.nn.NNConfig = conf
t.nn.dict = t.corpus
t.nn.transitions = t.ts
t.EvalPerIter = conf.EvalPerIteration
}
return f
}
// WithLemmatizer sets the lemmatizer option on the Trainer
func WithLemmatizer(l lingo.Lemmatizer) TrainerConsOpt {
f := func(t *Trainer) {
// cannot pass in itself!
if T, ok := l.(*Trainer); ok && T == t {
panic("Recursive definition of lemmatizer (trying to set the t.lemmatizer = T) !")
}
t.l = l
}
return f
}
// WithStemmer sets up the stemmer option on the DependencyParser
func WithStemmer(s lingo.Stemmer) TrainerConsOpt {
f := func(t *Trainer) {
// cannot pass in itself
if T, ok := s.(*Trainer); ok && T == t {
panic("Recursive setting of stemmer! (Trying to set t.stemmer = T)")
}
t.s = s
}
return f
}
// WithCluster sets the brown cluster options for the DependencyParser
func WithCluster(c map[string]lingo.Cluster) TrainerConsOpt {
f := func(t *Trainer) {
t.c = c
}
return f
}
// WithCorpus creates a Trainer with a corpus
func WithCorpus(c *corpus.Corpus) TrainerConsOpt {
f := func(t *Trainer) {
t.corpus = c
t.nn.dict = c
}
return f
}
// WithGeneratedCorpus creates a Trainer's corpus from a list of SentenceTags. The corpus will be generated from the SentenceTags
func WithGeneratedCorpus(sts ...treebank.SentenceTag) TrainerConsOpt {
f := func(t *Trainer) {
dict := corpus.GenerateCorpus(sts)
if t.corpus == nil {
t.corpus = dict
} else {
t.corpus.Merge(dict)
}
t.nn.dict = t.corpus
}
return f
}
// Trainer trains a model
type Trainer struct {
trainingSet []treebank.SentenceTag
crossValSet []treebank.SentenceTag
once sync.Once
*Model
// Training configuration
EvalPerIter int // for cross validation - evaluate results every n epochs
PassDirect bool // Pass on the costs directly to the cost channel? If false, an average will be used
SaveBest string // SaveBest is the filename that will be saved. If it's empty then the best-while-training will not be saved
// fixer
l lingo.Lemmatizer
s lingo.Stemmer
c map[string]lingo.Cluster
err chan error
cost chan float64
perf chan Performance
}
// NewTrainer creates a new Trainer.
func NewTrainer(opts ...TrainerConsOpt) *Trainer {
t := new(Trainer)
// set up the default model
t.Model = new(Model)
t.corpus = KnownWords
t.ts = transitions
// set up the neural network
t.nn = new(neuralnetwork2)
t.nn.NNConfig = DefaultNNConfig
t.nn.transitions = transitions
t.nn.dict = KnownWords
for _, opt := range opts {
opt(t)
}
return t
}
// Lemmatize implemnets lingo.Lemmatizer
func (t *Trainer) Lemmatize(a string, pt lingo.POSTag) ([]string, error) {
if t.l == nil {
return nil, componentUnavailable("Lemmatizer")
}
return t.l.Lemmatize(a, pt)
}
// Stem implements lingo.Stemmer
func (t *Trainer) Stem(a string) (string, error) {
if t.s == nil {
return "", componentUnavailable("Stemmer")
}
return t.s.Stem(a)
}
// Clusters implements lingo.Fixer
func (t *Trainer) Clusters() (map[string]lingo.Cluster, error) {
if t.c == nil {
return nil, componentUnavailable("Clusters")
}
return t.c, nil
}
/* Getters */
// Cost returns a channel of costs for monitoring the training. If the PassDirect field in the trainer is set to true
// then the costs are directly returned. Otherwise the costs are averaged over the epoch.
func (t *Trainer) Cost() <-chan float64 {
if t.cost == nil {
t.cost = make(chan float64)
}
return t.cost
}
// Perf returns a channel of Performance for monitoring the training.
func (t *Trainer) Perf() <-chan Performance {
if t.perf == nil {
t.perf = make(chan Performance)
}
return t.perf
}
/* Methods */
// Init initializes the DependencyParser with a corpus and a neural network config
func (t *Trainer) Init() (err error) {
f := func() {
err = t.nn.init()
}
t.once.Do(f)
return
}
// Train trains a model.
//
// If a cross validation set is provided, it will automatically train with the cross validation set
func (t *Trainer) Train(epochs int) error {
if err := t.pretrainCheck(); err != nil {
return err
}
if len(t.crossValSet) > 0 {
return t.crossValidateTrain(epochs)
}
return t.train(epochs)
}
// TrainWithoutCrossValidation trains a model without cross validation.
func (t *Trainer) TrainWithoutCrossValidation(epochs int) error {
return t.train(epochs)
}
// train simply trains the model without having a cross validation.
func (t *Trainer) train(epochs int) error {
var epochChan chan struct{}
if t.cost != nil {
defer func() {
close(t.cost)
t.cost = nil
}()
epochChan = t.handleCosts()
if epochChan != nil {
defer close(epochChan)
}
}
examples := makeExamples(t.trainingSet, t.nn.NNConfig, t.nn.dict, t.ts, t)
for e := 0; e < epochs; e++ {
if err := t.nn.train(examples); err != nil {
return err
}
if epochChan != nil {
epochChan <- struct{}{}
}
shuffleExamples(examples)
}
return nil
}
// crossValidateTrain trains the model but also does cross validation to ensure overfitting don't happen.
func (t *Trainer) crossValidateTrain(epochs int) error {
if t.perf != nil {
defer func() {
close(t.perf)
t.perf = nil
}()
}
var epochChan chan struct{}
if t.cost != nil {
defer func() {
close(t.cost)
t.cost = nil
}()
epochChan = t.handleCosts()
if epochChan != nil {
defer close(epochChan)
}
}
examples := makeExamples(t.trainingSet, t.nn.NNConfig, t.nn.dict, t.ts, t)
var best Performance
for e := 0; e < epochs; e++ {
if err := t.nn.train(examples); err != nil {
return err
}
if t.EvalPerIter > 0 && e%t.EvalPerIter == 0 || e == epochs-1 {
perf := t.crossValidate(t.crossValSet)
// if there is a channel to report back the performance, send it down
if t.perf != nil {
perf.Iter = e
t.perf <- perf
}
if perf.UAS > best.UAS {
best = perf
if t.SaveBest != "" {
f, err := os.Create(t.SaveBest)
if err != nil {
err = errors.Wrapf(err, "Unable to open SaveBest file %q", t.SaveBest)
return err
}
t.Model.SaveWriter(f)
}
}
}
if epochChan != nil {
epochChan <- struct{}{}
}
shuffleExamples(examples)
}
return nil
}
// pretrainCheck checks if everything is sane
func (t *Trainer) pretrainCheck() error {
// check
if t.nn == nil || !t.nn.initialized() {
return errors.Errorf("DependencyParser not init()'d. Perhaps you forgot to call .Init() somewhere?")
}
if len(t.trainingSet) == 0 {
return errors.Errorf("Cannot train with no training data set")
}
return nil
}
// handleCosts handles the costs from the neural network in two ways:
// 1. pass: directly passes on the costs (which may come from multiple batches in an epoch)
// 2. mean: calculates the mean of the costs and passes it on into d.cost
//
// If d.cost is nil, it simply returns. This method should be called after a check that d.cost is not nil
func (t *Trainer) handleCosts() (epochChan chan struct{}) {
nncost := t.nn.costProgress()
if t.PassDirect {
go func() {
for cost := range nncost {
switch c := cost.Data().(type) {
case float32:
t.cost <- float64(c)
case float64:
t.cost <- c
default:
// this should NEVER happen
panic(fmt.Sprintf("Unhandled cost type %T", c))
}
}
}()
} else {
epochChan = make(chan struct{})
// it collects the costs until the epoch chan signals that an epoch is done. Then the cost is averaged and sent down the d.cost channel
go func(epochChan chan struct{}) {
var collected []float64
for {
select {
case cost := <-nncost:
switch c := cost.Data().(type) {
case float32:
collected = append(collected, float64(c))
case float64:
collected = append(collected, c)
default:
// this should NEVER happen
panic(fmt.Sprintf("Unhandled cost type %T", c))
}
case <-epochChan:
var avg float64
for _, cost := range collected {
avg += cost
}
if len(collected) > 0 {
avg /= float64(len(collected))
}
t.cost <- avg
collected = collected[:0]
}
}
}(epochChan)
}
return
}