-
Notifications
You must be signed in to change notification settings - Fork 4
/
Trainer.js
280 lines (231 loc) · 8.4 KB
/
Trainer.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
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
// import * as tf from '@tensorflow/tfjs';
// import * as tfvis from '@tensorflow/tfjs-vis';
import * as _ from 'lodash-es';
// console.log(tf.version);
// console.log(tfvis.version);
const EPOCHS = 200;
const BATCH_SIZE = 200;
const N_FEATURES = 5;
const N_STEPS = 200;
const SEGMENT_SIZE = 25;
const N_SEGMENTS = 2;
const SEED = undefined;
const MODEL_URL =
"https://raw.githubusercontent.com/DJCordhose/ux-by-tfjs/master/model/ux.json";
const CONVERTED_MODEL_URL =
"https://raw.githubusercontent.com/DJCordhose/ux-by-tfjs/master/model/model.json";
const CLICK_MODEL_URL =
"https://raw.githubusercontent.com/DJCordhose/ux-by-tfjs/master/model/click/model.json";
const CLICK_MODEL_OVERFIT_URL =
"https://raw.githubusercontent.com/DJCordhose/ux-by-tfjs/master/model/click-overfit/model.json";
class Trainer {
constructor() {
this.init();
this.loadClickModel();
}
init() {
this.model = tf.sequential();
window.trainer = this;
this.model.add(
// tf.layers.gru({
// name: "gru1",
// activation: 'tanh',
// // activation: 'relu',
// // kernelInitializer: tf.initializers.glorotNormal({ seed: SEED }),
// units: 50,
// inputShape: [SEGMENT_SIZE, N_FEATURES],
// dropout: 0.2
// })
// slower to train and worse evaluation, but really good real world performance
// tf.layers.lstm({
// name: "lstm1",
// activation: 'tanh',
// // activation: 'relu',
// kernelInitializer: tf.initializers.glorotNormal({ seed: SEED }),
// units: 50,
// inputShape: [SEGMENT_SIZE, N_FEATURES],
// dropout: 0.1
// })
// trains fast, bad evaluation, but in real life does what we expect, only uses very recent history, generalizing great by proximity
tf.layers.simpleRNN({
name: "rnn1",
activation: 'tanh',
// activation: 'relu',
// kernelInitializer: tf.initializers.glorotNormal({ seed: SEED }),
units: 50,
// units: 75,
inputShape: [SEGMENT_SIZE, N_FEATURES],
// dropout: 0.6
dropout: 0.1
})
);
this.model.add(tf.layers.batchNormalization());
this.model.add(
tf.layers.dense({
name: "softmax",
units: 3,
kernelInitializer: tf.initializers.glorotNormal({ seed: SEED }),
activation: "softmax"
})
);
// this.model.summary();
}
prepareData(data) {
console.log('preparing datasets', data.length)
// make sure validation isn't always the last clicks
data = _.shuffle(data);
const xs = data.map(({ x }) => Object.values(x));
// console.log(xs)
// xs nDatasets, 200, 5
// segmentSize = 50
// nSegments = 200 / segmentSize
// xsNew: nDatasets * nSegments, segmentSize, 5
let newXs = [];
xs.forEach(x => {
let chunks = _.chunk(x, SEGMENT_SIZE);
chunks = chunks.slice(chunks.length - N_SEGMENTS)
newXs = newXs.concat(chunks);
});
// ys nDatasets, 1
// ysNew (nDatasets * nSegments) * 1
const ys = data.map(({ y }) => y - 1);
let newYs = [];
ys.forEach(y => {
const labels = new Array(N_SEGMENTS).fill(y);
newYs = newYs.concat(labels);
});
const uniqLabels = _.sortBy(_.uniq(newYs));
console.log(uniqLabels)
console.assert(newXs.length === newYs.length, 'input and output should have the same length');
// console.assert(newXs.length === xs.length * N_STEPS / SEGMENT_SIZE, 'data size should be properly expanded');
console.assert(_.isEqual(uniqLabels, [0, 1, 2]), 'labels should only be 0, 1, or 2');
const X = tf.tensor3d(newXs);
const y = tf.tensor1d(newYs, "int32");
return {
X,
y,
xs: newXs,
ys: newYs
}
}
async train(data) {
const { X, y, xs, ys } = this.prepareData(data);
const consoleCallbacks = {
onEpochEnd: (...args) => {
console.log(...args);
},
// onBatchEnd: (...args) => {
// console.log(...args);
// },
// onEpochBegin: iteration => {
// // console.clear();
// console.log(iteration);
// }
};
const metrics = ["loss", "val_loss", "acc", "val_acc"];
const container = {
name: 'show.fitCallbacks',
tab: 'Training',
styles: {
height: '1000px'
}
}
const vizCallbacks = tfvis.show.fitCallbacks(container, metrics);
this.model.compile({
loss: "sparseCategoricalCrossentropy",
optimizer: "adam",
metrics: ["accuracy"]
});
const history = await this.model.fit(X, y, {
epochs: EPOCHS,
validationSplit: 0.2,
batchSize: BATCH_SIZE,
shuffle: true,
callbacks: vizCallbacks
// callbacks: consoleCallbacks
});
const { acc, loss, val_acc, val_loss } = history.history;
const summary = `accuracy: ${
acc[acc.length - 1]
}, accuracy on unknown data: ${val_acc[val_acc.length - 1]}`;
console.log(summary);
const sample = xs[0]
// console.log(sample);
console.log(await this.predict(sample))
console.log(ys[0])
}
async save() {
await this.model.save("indexeddb://ux");
console.log(await tf.io.listModels());
}
async download() {
await this.model.save("downloads://ux");
}
async load() {
this.model = await tf.loadLayersModel('indexeddb://ux');
console.log('model loaded locally')
}
async loadRemote() {
// const url = CONVERTED_MODEL_URL;
const url = MODEL_URL;
console.log(`loading remote model from ${url}`)
// https://js.tensorflow.org/api/latest/#loadGraphModel
this.model = await tf.loadLayersModel(url);
}
async upload() {
const jsonUpload = document.getElementById('json-upload');
const weightsUpload = document.getElementById('weights-upload');
this.model = await tf.loadLayersModel(
tf.io.browserFiles([jsonUpload.files[0], weightsUpload.files[0]]));
console.log('model uploaded successfully')
}
async predict(X) {
const prediction = await this.model.predict(tf.tensor3d([X])).data();
console.log(prediction)
return prediction;
}
showModel() {
const surface = {
name: 'Model Summary',
tab: 'Model'
};
tfvis.show.modelSummary(surface, this.model);
}
showVisor() {
const visor = tfvis.visor();
visor.toggle();
}
async showEvaluation(data) {
const { X, y, xs, ys } = this.prepareData(data);
const classNames = ["Left Button", "Middle Button", "Right Button"];
const yTrue = y;
const yPred = this.model.predict(X).argMax([-1]);
const confusionMatrix = await tfvis.metrics.confusionMatrix(yTrue, yPred);
const container = {
name: 'Confusion Matrix',
tab: 'Evaluation'
};
tfvis.show.confusionMatrix(container, confusionMatrix, classNames);
const classAccuracy = await tfvis.metrics.perClassAccuracy(yTrue, yPred);
const accuracyContainer = {
name: 'Accuracy',
tab: 'Evaluation'
};
tfvis.show.perClassAccuracy(accuracyContainer, classAccuracy, classNames);
}
async loadClickModel() {
const url = CLICK_MODEL_URL;
// const url = CLICK_MODEL_OVERFIT_URL
console.log(`loading click model from ${url}`)
this.clickModel = await tf.loadLayersModel(url);
}
async predictClick(X) {
if (!this.clickModel) {
await this.loadClickModel();
}
const prediction = await this.clickModel.predict(tf.tensor([X])).data();
console.log(prediction)
return prediction;
}
}
export const trainer = new Trainer()