forked from BrainJS/brain.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain-stream.js
177 lines (151 loc) · 4.4 KB
/
train-stream.js
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
import { Writable } from 'stream';
import lookup from './lookup';
/**
*
* @param opts
* @returns {TrainStream}
* @constructor
*/
export default class TrainStream extends Writable {
constructor(opts) {
super({
objectMode: true
});
opts = opts || {};
// require the neuralNetwork
if (!opts.neuralNetwork) {
throw new Error('no neural network specified');
}
this.neuralNetwork = opts.neuralNetwork;
this.dataFormatDetermined = false;
this.inputKeys = [];
this.outputKeys = []; // keeps track of keys seen
this.i = 0; // keep track of the for loop i variable that we got rid of
this.iterations = opts.iterations || 20000;
this.errorThresh = opts.errorThresh || 0.005;
this.log = opts.log ? (typeof opts.log === 'function' ? opts.log : console.log) : false;
this.logPeriod = opts.logPeriod || 10;
this.callback = opts.callback;
this.callbackPeriod = opts.callbackPeriod || 10;
this.floodCallback = opts.floodCallback;
this.doneTrainingCallback = opts.doneTrainingCallback;
this.size = 0;
this.count = 0;
this.sum = 0;
this.on('finish', this.finishStreamIteration.bind(this));
return this;
}
/**
* _write expects data to be in the form of a datum. ie. {input: {a: 1 b: 0}, output: {z: 0}}
* @param chunk
* @param enc
* @param next
* @returns {*}
* @private
*/
_write(chunk, enc, next) {
if (!chunk) { // check for the end of one iteration of the stream
this.emit('finish');
return next();
}
if (!this.dataFormatDetermined) {
this.size++;
this.inputKeys = uniques(this.inputKeys.slice(0).concat(Object.keys(chunk.input)));
this.outputKeys = uniques(this.outputKeys.slice(0).concat(Object.keys(chunk.output)));
this.firstDatum = this.firstDatum || chunk;
return next();
}
this.count++;
let data = this.neuralNetwork.formatData(chunk);
this.trainDatum(data[0]);
// tell the Readable Stream that we are ready for more data
next();
}
/**
*
* @param datum
*/
trainDatum(datum) {
let err = this.neuralNetwork.trainPattern(datum.input, datum.output);
this.sum += err;
}
/**
*
* @returns {*}
*/
finishStreamIteration() {
if (this.dataFormatDetermined && this.size !== this.count) {
this.log('This iteration\'s data length was different from the first.');
}
if (!this.dataFormatDetermined) {
// create the lookup
this.neuralNetwork.inputLookup = lookup.lookupFromArray(this.inputKeys);
if(this.firstDatum.output.constructor !== Array){
this.neuralNetwork.outputLookup = lookup.lookupFromArray(this.outputKeys);
}
let data = this.neuralNetwork.formatData(this.firstDatum);
let sizes = [];
let inputSize = data[0].input.length;
let outputSize = data[0].output.length;
let hiddenSizes = this.hiddenSizes;
if (!hiddenSizes) {
sizes.push(Math.max(3, Math.floor(inputSize / 2)));
} else {
hiddenSizes.forEach(size => {
sizes.push(size);
});
}
sizes.unshift(inputSize);
sizes.push(outputSize);
this.dataFormatDetermined = true;
this.neuralNetwork.initialize(sizes);
if (typeof this.floodCallback === 'function') {
this.floodCallback();
}
return;
}
let error = this.sum / this.size;
if (this.log && (this.i % this.logPeriod == 0)) {
this.log('iterations:', this.i, 'training error:', error);
}
if (this.callback && (this.i % this.callbackPeriod == 0)) {
this.callback({
error: error,
iterations: this.i
});
}
this.sum = 0;
this.count = 0;
// update the iterations
this.i++;
// do a check here to see if we need the stream again
if (this.i < this.iterations && error > this.errorThresh) {
if (typeof this.floodCallback === 'function') {
return this.floodCallback();
}
} else {
// done training
if (typeof this.doneTrainingCallback === 'function') {
return this.doneTrainingCallback({
error: error,
iterations: this.i
});
}
}
}
}
/**
*
* http://stackoverflow.com/a/21445415/1324039
* @param arr
* @returns {Array}
*/
function uniques(arr) {
let a = [];
for (let i=0, l=arr.length; i<l; i++) {
if (a.indexOf(arr[i]) === -1 && arr[i] !== '') {
a.push(arr[i]);
}
}
return a;
}