-
Notifications
You must be signed in to change notification settings - Fork 0
/
nn_test.go
483 lines (421 loc) · 9.9 KB
/
nn_test.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
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
package seafan
import (
"fmt"
"github.com/invertedv/utilities"
"math"
"os"
"testing"
"github.com/invertedv/chutils"
"github.com/invertedv/chutils/file"
"github.com/stretchr/testify/assert"
"gonum.org/v1/gonum/stat"
)
func chPipe(bSize int, fileName string) *ChData {
dataPath := os.Getenv("data") // path to data directory
f, e := os.Open(dataPath + "/" + fileName)
if e != nil {
panic(e)
}
// set up chutils file reader
rdr := file.NewReader(fileName, ',', '\n', 0, 0, 1, 0, f, 0)
e = rdr.Init("", chutils.MergeTree)
if e != nil {
panic(e)
}
// determine data types
e = rdr.TableSpec().Impute(rdr, 0, .99)
if e != nil {
panic(e)
}
ch := NewChData("Test ch Pipeline", WithBatchSize(bSize),
WithReader(rdr), WithCycle(true),
WithCats("y", "y1", "y2"),
WithOneHot("yoh", "y"),
WithOneHot("y1oh", "y1"))
// initialize pipeline
e = ch.Init()
if e != nil {
panic(e)
}
return ch
}
func TestNNModel_Save(t *testing.T) {
Verbose = false
pipe := chPipe(100, "test1.csv")
mod := ModSpec{
"Input(x1+x2+x3+x4)",
"FC(size:2, activation:softmax)",
"Target(yoh)",
}
//
nn, e := NewNNModel(mod, pipe, true)
assert.Nil(t, e)
WithCostFn(CrossEntropy)(nn)
e = nn.Save("/home/will/tmp/testnn")
assert.Nil(t, e)
assert.Equal(t, 2, nn.OutputCols()) // nn.Cols())
exp := make([]float64, 0)
for _, n := range nn.paramsW {
x := n.Nodes()[0].Value().Data().([]float64)
for ind := 0; ind < len(x); ind++ {
exp = append(exp, math.Round(x[ind]*100.0)/100.0)
}
}
nn1, e := LoadNN("/home/will/tmp/testnn", pipe, false)
assert.Nil(t, e)
act := make([]float64, 0)
for _, n := range nn1.paramsW {
x := n.Nodes()[0].Value().Data().([]float64)
for ind := 0; ind < len(x); ind++ {
act = append(act, math.Round(x[ind]*100.0)/100.0)
}
}
assert.ElementsMatch(t, exp, act)
assert.ElementsMatch(t, mod, nn.construct)
}
func TestFit_Do(t *testing.T) {
Verbose = false
pipe := chPipe(100, "test1.csv")
mod := ModSpec{
"Input(x1+x2+x3+x4)",
"FC(size:2, activation:softmax)",
"Target(yoh)",
}
nn, e := NewNNModel(mod, pipe, true)
assert.Nil(t, e)
WithCostFn(CrossEntropy)(nn)
epochs := 150
ft := NewFit(nn, epochs, pipe)
e = ft.Do()
assert.Nil(t, e)
wts := []float64{-2.06, -3.5, 1, -0.08} // glm logistic estimates
n := nn.G().ByName("lWeights1").Nodes()[0].Value().Data().([]float64)
for ind, w := range wts {
assert.InEpsilon(t, n[ind], w, .15)
}
}
func ExampleWithOneHot() {
// This example shows a model that incorporates a feature (x4) as one-hot and an embedding
Verbose = false
bSize := 100
// generate a Pipeline of type *ChData that reads test.csv in the data directory
pipe := chPipe(bSize, "test1.csv")
// The feature x4 takes on values 0,1,2,...19. chPipe treats this a continuous feature.
// Let's override that and re-initialize the pipeline.
WithCats("x4")(pipe)
WithOneHot("x4oh", "x4")(pipe)
if e := pipe.Init(); e != nil {
panic(e)
}
mod := ModSpec{
"Input(x1+x2+x3+x4oh)",
"FC(size:2, activation:softmax)",
"Target(yoh)",
}
//
fmt.Println("x4 as one-hot")
nn, e := NewNNModel(mod, pipe, true)
if e != nil {
panic(e)
}
fmt.Println(nn)
fmt.Println("x4 as embedding")
mod = ModSpec{
"Input(x1+x2+x3+E(x4oh,3))",
"FC(size:2, activation:softmax)",
"Target(yoh)",
}
nn, e = NewNNModel(mod, pipe, true)
if e != nil {
panic(e)
}
fmt.Println(nn)
// Output:
//x4 as one-hot
//
//Inputs
//Field x1
// continuous
//
//Field x2
// continuous
//
//Field x3
// continuous
//
//Field x4oh
// one-hot
// derived from feature x4
// length 20
//
//Target
//Field yoh
// one-hot
// derived from feature y
// length 2
//
//Model Structure
//Input(x1+x2+x3+x4oh)
//FC(size:2, activation:softmax)
//Target(yoh)
//
//Batch size: 100
//24 FC parameters
//0 Embedding parameters
//
//x4 as embedding
//
//Inputs
//Field x1
// continuous
//
//Field x2
// continuous
//
//Field x3
// continuous
//
//Field x4oh
// embedding
// derived from feature x4
// length 20
// embedding dimension of 3
//
//Target
//Field yoh
// one-hot
// derived from feature y
// length 2
//
//Model Structure
//Input(x1+x2+x3+E(x4oh,3))
//FC(size:2, activation:softmax)
//Target(yoh)
//
//Batch size: 100
//7 FC parameters
//60 Embedding parameters
}
func ExampleWithOneHot_example2() {
// This example incorporates a drop out layer
Verbose = false
bSize := 100
// generate a Pipeline of type *ChData that reads test.csv in the data directory
pipe := chPipe(bSize, "test1.csv")
// generate model: target and features. Target yoh is one-hot with 2 levels
mod := ModSpec{
"Input(x1+x2+x3+x4)",
"FC(size:3, activation:relu)",
"DropOut(.1)",
"FC(size:2, activation:softmax)",
"Target(yoh)",
}
nn, e := NewNNModel(mod, pipe, true,
WithCostFn(CrossEntropy),
WithName("Example With Dropouts"))
if e != nil {
panic(e)
}
fmt.Println(nn)
// Output:
//Example With Dropouts
//Inputs
//Field x1
// continuous
//
//Field x2
// continuous
//
//Field x3
// continuous
//
//Field x4
// continuous
//
//Target
//Field yoh
// one-hot
// derived from feature y
// length 2
//
//Model Structure
//Input(x1+x2+x3+x4)
//FC(size:3, activation:relu)
//DropOut(.1)
//FC(size:2, activation:softmax)
//Target(yoh)
//
//Cost function: CrossEntropy
//
//Batch size: 100
//19 FC parameters
//0 Embedding parameters
}
func ExampleFit_Do() {
Verbose = false
bSize := 100
// generate a Pipeline of type *ChData that reads test.csv in the data directory
pipe := chPipe(bSize, "test1.csv")
// generate model: target and features. Target yoh is one-hot with 2 levels
mod := ModSpec{
"Input(x1+x2+x3+x4)",
"FC(size:3, activation:relu)",
"DropOut(.1)",
"FC(size:2, activation:softmax)",
"Target(yoh)",
}
// model is straight-forward with no hidden layers or dropouts.
nn, e := NewNNModel(mod, pipe, true, WithCostFn(CrossEntropy))
if e != nil {
panic(e)
}
epochs := 150
ft := NewFit(nn, epochs, pipe)
e = ft.Do()
if e != nil {
panic(e)
}
// Plot the in-sample cost in a browser (default: firefox)
e = ft.InCosts().Plot(&utilities.PlotDef{Title: "In-Sample Cost Curve", Height: 1200, Width: 1200,
Show: true, XTitle: "epoch", YTitle: "Cost"}, true)
if e != nil {
panic(e)
}
// Output:
}
func ExampleFit_Do_example2() {
// This example demonstrates how to use a validation sample for early stopping
Verbose = false
bSize := 100
// generate a Pipeline of type *ChData that reads test.csv in the data directory
mPipe := chPipe(bSize, "test1.csv")
vPipe := chPipe(1000, "testVal.csv")
// generate model: target and features. Target yoh is one-hot with 2 levels
mod := ModSpec{
"Input(x1+x2+x3+x4)",
"FC(size:3, activation:relu)",
"DropOut(.1)",
"FC(size:2, activation:softmax)",
"Target(yoh)",
}
nn, e := NewNNModel(mod, mPipe, true, WithCostFn(CrossEntropy))
if e != nil {
panic(e)
}
epochs := 150
ft := NewFit(nn, epochs, mPipe)
WithValidation(vPipe, 10)(ft)
e = ft.Do()
if e != nil {
panic(e)
}
// Plot the in-sample cost in a browser (default: firefox)
e = ft.InCosts().Plot(&utilities.PlotDef{Title: "In-Sample Cost Curve", Height: 1200, Width: 1200,
Show: true, XTitle: "epoch", YTitle: "Cost"}, true)
if e != nil {
panic(e)
}
e = ft.OutCosts().Plot(&utilities.PlotDef{Title: "Validation Sample Cost Curve", Height: 1200, Width: 1200,
Show: true, XTitle: "epoch", YTitle: "Cost"}, true)
if e != nil {
panic(e)
}
// Output:
}
func ExamplePredictNN() {
// This example demonstrates fitting a regression model and predicting on new data
Verbose = false
bSize := 100
// generate a Pipeline of type *ChData that reads test.csv in the data directory
mPipe := chPipe(bSize, "test1.csv")
vPipe := chPipe(1000, "testVal.csv")
// This model is OLS
mod := ModSpec{
"Input(x1+x2+x3+x4)",
"FC(size:1)",
"Target(ycts)",
}
// model is straight-forward with no hidden layers or dropouts.
nn, e := NewNNModel(mod, mPipe, true, WithCostFn(RMS))
if e != nil {
panic(e)
}
epochs := 150
ft := NewFit(nn, epochs, mPipe)
e = ft.Do()
if e != nil {
panic(e)
}
sf := os.TempDir() + "/nnTest"
e = nn.Save(sf)
if e != nil {
panic(e)
}
pred, e := PredictNN(sf, vPipe, false)
if e != nil {
panic(e)
}
fmt.Printf("out-of-sample correlation: %0.2f\n", stat.Correlation(pred.FitSlice(), pred.ObsSlice(), nil))
_ = os.Remove(sf + "P.nn")
if e != nil {
panic(e)
}
_ = os.Remove(sf + "S.nn")
// Output:
// out-of-sample correlation: 0.84
}
func ExampleWithCallBack() {
// This example shows how to create a callback during the fitting phase (fit.Do).
// The callback is called at the end of each epoch. The callback below loads a new dataset after
// epoch 100.
Verbose = false
bSize := 100
// generate a Pipeline of type *ChData that reads test.csv in the data directory
mPipe := chPipe(bSize, "test1.csv")
// This callback function replaces the initial dataset with newData.csv after epoch 2500
cb := func(c Pipeline) {
switch d := c.(type) {
case *ChData:
if d.Epoch(-1) == 100 {
dataPath := os.Getenv("data") // path to data directory
fileName := dataPath + "/testVal.csv"
f, e := os.Open(fileName)
if e != nil {
panic(e)
}
rdrx := file.NewReader(fileName, ',', '\n', 0, 0, 1, 0, f, 0)
if e := rdrx.Init("", chutils.MergeTree); e != nil {
panic(e)
}
if e := rdrx.TableSpec().Impute(rdrx, 0, .99); e != nil {
panic(e)
}
rows, _ := rdrx.CountLines()
fmt.Println("New data at end of epoch ", d.Epoch(-1))
fmt.Println("Number of rows ", rows)
WithReader(rdrx)(d)
}
}
}
WithCallBack(cb)(mPipe)
// This model is OLS
mod := ModSpec{
"Input(x1+x2+x3+x4)",
"FC(size:1)",
"Target(ycts)",
}
// model is straight-forward with no hidden layers or dropouts.
nn, e := NewNNModel(mod, mPipe, true, WithCostFn(RMS))
if e != nil {
panic(e)
}
epochs := 150
ft := NewFit(nn, epochs, mPipe)
e = ft.Do()
if e != nil {
panic(e)
}
// Output:
//New data at end of epoch 100
//Number of rows 1000
}