This repository has been archived by the owner on Oct 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
/
ModelBuilder.ts
351 lines (294 loc) · 10.7 KB
/
ModelBuilder.ts
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
/**
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
import {
Array1D, Array4D,
CostReduction,
FeedEntry,
Graph,
InCPUMemoryShuffledInputProviderBuilder,
InMemoryDataset,
MetricReduction,
NDArray,
NDArrayInitializer,
NDArrayMathGPU,
Optimizer,
Session,
Scalar,
SGDOptimizer,
Tensor,
util, VarianceScalingInitializer, ZerosInitializer,
} from 'deeplearn';
import {EventEmitter} from 'eventemitter3';
import {GraphWeights} from './GraphSaverLoader';
import SpeechCommandDataset from './SpeechCommandDataset';
// Values from model-builder.ts.
const BATCH_SIZE = 64;
const NUM_BATCHES = 10000;
const MIN_COST_VALUE = 0.1;
const TRAIN_TEST_RATIO = 0.9;
const LEARNING_RATE = 0.01;
export default class ModelBuilder {
modelInitialized: boolean
session: Session
graph: Graph
optimizer: Optimizer
math: NDArrayMathGPU
inputShape: number[]
labelShape: number[]
learningRate: number
inputTensor: Tensor
labelTensor: Tensor
regularizationTensor: Tensor
predictionTensor: Tensor
costTensor: Tensor
accuracyTensor: Tensor
nodeIndex: number
dataSet: SpeechCommandDataset
totalTimeSec: number
isTraining: boolean
progress: EventEmitter
constructor(inputShape, labelShape, dataSet=null) {
this.nodeIndex = 0;
this.dataSet = dataSet;
// Dimensions of the Mel spectrogram we feed into this model.
this.inputShape = inputShape;
// Shape of the 1D one-hot encoded labels.
this.labelShape = labelShape;
this.isTraining = false;
this.math = new NDArrayMathGPU();
this.progress = new EventEmitter();
this.learningRate = LEARNING_RATE;
}
createModel(loadedWeights: GraphWeights=null) {
if (this.session != null) {
this.session.dispose();
}
// Reset the node index.
this.nodeIndex = 0;
this.modelInitialized = false;
this.graph = new Graph();
const g = this.graph;
this.inputTensor = g.placeholder('input', this.inputShape);
this.labelTensor = g.placeholder('label', this.labelShape);
// Construct the hidden layers.
let network = this.inputTensor;
network = this.addConv2d(g, network, 8, loadedWeights);
const reg1 = this.addRegularization(g, network);
network = this.addRelu(g, network);
network = this.addMaxPool(g, network);
network = this.addConv2d(g, network, 16, loadedWeights)
const reg2 = this.addRegularization(g, network);
network = this.addRelu(g, network);
network = this.addMaxPool(g, network);
network = this.addFlatten(g, network);
network = this.addFullyConnected(g, network, loadedWeights);
const reg3 = this.addRegularization(g, network);
this.predictionTensor = network;
// Add a regularization parameter.
this.regularizationTensor = g.add(reg1, reg2, reg3);
const softmaxCrossEntropyCostTensor =
g.softmaxCrossEntropyCost(this.predictionTensor, this.labelTensor);
//this.costTensor = g.add(softmaxCrossEntropyCostTensor, this.regularizationTensor);
this.costTensor = softmaxCrossEntropyCostTensor;
this.accuracyTensor =
g.argmaxEquals(this.predictionTensor, this.labelTensor);
this.session = new Session(g, this.math);
this.modelInitialized = true;
}
setLearningRate(learningRate: number) {
this.learningRate = learningRate;
}
async startTraining() {
console.log('startTraining');
const trainingData = this.getTrainingData();
const trainingShuffledInputProviderGenerator =
new InCPUMemoryShuffledInputProviderBuilder(trainingData);
const [trainingInputProvider, trainingLabelProvider] =
trainingShuffledInputProviderGenerator.getInputProviders();
const trainingFeeds = [
{tensor: this.inputTensor, data: trainingInputProvider},
{tensor: this.labelTensor, data: trainingLabelProvider}
];
this.isTraining = true;
let minCost = Infinity;
let maxAccuracy = -Infinity;
// Training is broken up into batches.
// Before we start training, we need to provide an optimizer. This is the
// object that is responsible for updating weights. The learning rate param
// is a value that represents how large of a step to make when updating
// weights. If this is too big, you may overstep and oscillate. If it is too
// small, the model may take a long time to train.
const optimizer = new SGDOptimizer(this.learningRate);
console.log(`Training ${NUM_BATCHES} batches of size ${BATCH_SIZE}` +
` at rate: ${this.learningRate}.`);
for (let i = 0; i < NUM_BATCHES; i++) {
// Train takes a cost tensor to minimize; this call trains one batch and
// returns the average cost of the batch as a Scalar.
const costValue = this.session.train(
this.costTensor, trainingFeeds,
BATCH_SIZE, optimizer, CostReduction.MEAN);
const cost = parseFloat(await costValue.data());
console.log(`#${i}: cost: ${cost.toFixed(3)}.`);
if (cost < minCost) {
minCost = cost;
}
if (!this.isTraining) {
break;
}
if (i % 20 == 0) {
const accuracy = await this.getTestAccuracy(50);
if (accuracy > maxAccuracy) {
maxAccuracy = accuracy;
}
console.log(`#${i}: accuracy: ${accuracy.toFixed(3)},`
+ ` maxAccuracy: ${maxAccuracy.toFixed(3)}.`);
this.progress.emit('accuracy', {accuracy, maxAccuracy});
}
this.progress.emit('cost', {cost, minCost});
}
this.isTraining = false;
}
async getTestAccuracy(limit?: number) {
const testData = this.getTestData();
const totalCount = testData[0].length;
if (!limit) {
limit = totalCount;
}
const count = Math.min(limit, totalCount);
let accurateCount = 0;
for (let i = 0; i < count; i++) {
const ind = Math.floor(Math.random() * totalCount);
const input = testData[0][ind];
const label = testData[1][ind];
const inferenceFeeds = [
{tensor: this.inputTensor, data: input},
{tensor: this.labelTensor, data: label},
];
const result = this.session.eval(this.accuracyTensor, inferenceFeeds);
/*
// Output regularization value for debugging.
const regularization = this.session.eval(this.regularizationTensor, inferenceFeeds);
console.log('regularizationTensor', regularization.dataSync());
*/
const accuracy = await result.data()
if (accuracy[0]) {
accurateCount += 1;
}
}
return (accurateCount / count);
}
stopTraining() {
console.log('Stopped training!');
this.isTraining = false;
}
private addConv2d(g: Graph, network: Tensor, outputDepth: number,
init: GraphWeights=null) {
// 5x5 square filter.
const fieldSize = 5;
const stride = 1;
const zeroPad = 2;
const wShape =
[fieldSize, fieldSize, network.shape[2], outputDepth];
const wName = `save-conv2d-${this.nodeIndex}-w`;
const bName = `save-conv2d-${this.nodeIndex}-b`;
let w = NDArray.randTruncatedNormal(wShape, 0, 0.1);
let b = Array1D.zeros([outputDepth]);
if (init) {
w = init[wName];
b = init[bName];
}
const wTensor = g.variable(wName, w);
const bTensor = g.variable(bName, b);
this.nodeIndex += 1;
return g.conv2d(
network, wTensor, bTensor, fieldSize, outputDepth,
stride, zeroPad);
}
private addRelu(g: Graph, network: Tensor) {
return g.relu(network);
}
private addMaxPool(g: Graph, network: Tensor) {
const fieldSize = 2;
// Was previously stride=2 in the MNIST network. Changed this value because
// of the input size.
const stride = 1;
const zeroPad = 0;
return g.maxPool(network, fieldSize, stride, zeroPad);
}
private addFlatten(g: Graph, network: Tensor) {
const size = util.sizeFromShape(network.shape);
return g.reshape(network, [size]);
}
private addFullyConnected(g: Graph, network: Tensor, init: GraphWeights=null) {
const inputSize = util.sizeFromShape(network.shape);
const hiddenUnits = this.labelShape[0];
let weightsInitializer, biasInitializer;
if (init) {
weightsInitializer = new NDArrayInitializer(init['save-fc1-weights']);
biasInitializer = new NDArrayInitializer(init['save-fc1-bias']);
} else {
weightsInitializer = new VarianceScalingInitializer();
biasInitializer = new ZerosInitializer();
}
const useBias = true;
return g.layers.dense(
'save-fc1', network, hiddenUnits, null, useBias, weightsInitializer,
biasInitializer);
}
private addRegularization(g: Graph, network: Tensor) {
const beta = 0.01;
const betaTensor = g.variable('beta', Scalar.new(beta));
return g.multiply(betaTensor, g.reduceSum(g.square(network)));
}
private getTestData(): NDArray[][] {
const data = this.dataSet.getData();
if (data == null) {
return null;
}
const [images, labels] = this.dataSet.getData() as [NDArray[], NDArray[]];
const start = Math.floor(TRAIN_TEST_RATIO * images.length);
return [images.slice(start), labels.slice(start)];
}
private getTrainingData(): NDArray[][] {
const [images, labels] = this.dataSet.getData() as [NDArray[], NDArray[]];
const end = Math.floor(TRAIN_TEST_RATIO * images.length);
return [images.slice(0, end), labels.slice(0, end)];
}
private getTrainingCount() {
const [images, labels] = this.dataSet.getData() as [NDArray[], NDArray[]];
return TRAIN_TEST_RATIO * images.length;
}
async startInference() {
const testData = this.getTestData();
console.log(`Running inference on ${testData.length} points.`);
const inferenceShuffledInputProviderGenerator =
new InCPUMemoryShuffledInputProviderBuilder(testData);
const [inferenceInputProvider, inferenceLabelProvider] =
inferenceShuffledInputProviderGenerator.getInputProviders();
const inferenceFeeds = [
{tensor: this.inputTensor, data: inferenceInputProvider},
{tensor: this.labelTensor, data: inferenceLabelProvider}
];
const result = this.session.eval(this.predictionTensor, inferenceFeeds);
console.log(await result.data());
}
predict(input: NDArray) {
const inferenceFeeds = [
{tensor: this.inputTensor, data: input}
];
return this.session.eval(this.predictionTensor, inferenceFeeds);
}
}