-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcnn.ts
354 lines (324 loc) · 11.1 KB
/
cnn.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
352
353
354
import { activationFunctions } from "./activation";
import { readFileSync, writeFileSync, existsSync } from "fs";
import { moveMessagePortToContext } from "worker_threads";
export class CNN {
layers: number[];
weights: Weights = []; // notation: w_lij is weight i from neuron j in layer l
previousDeltaWeights: Weights = [];
activation: Activation;
weightFile: string;
// debug
errors: number[] = [];
constructor(
inputSize: number,
hiddenLayerSizes: number[],
outputSize: number,
options: NNOptions
) {
const { activation, weightOptions } = options;
this.activation = activationFunctions[activation];
this.layers = [inputSize, ...hiddenLayerSizes, outputSize];
this.weights = this.getInitialWeights(weightOptions);
this.previousDeltaWeights = this.getInitialWeights({ fixedWeight: 0 });
}
detect(input: InputLayer): Layer {
const activatedInputs = input.map((i) => ({
activation: this.activation.primitive(i),
}));
const propagatedNetwork = this.propagate(activatedInputs);
const outputLayer = propagatedNetwork[propagatedNetwork.length - 1];
return outputLayer;
}
train(batch: Batch, learningRate: number, momentum: number) {
const batchSize = batch.length;
const batchDeltaWeights: Weights[] = batch.map(({ input, label }) => {
const activatedInputs = input.map((i) => ({
activation: this.activation.primitive(i),
}));
const propagatedNetwork = this.propagate(activatedInputs);
const deltaWeights: Weights = this.backpropagate(
propagatedNetwork,
label,
learningRate,
momentum
);
// debug
// const error = this.calculateError(
// propagatedNetwork[propagatedNetwork.length - 1],
// label
// );
// this.errors.push(error);
// this.logAllValues(propagatedNetwork, label)
return deltaWeights;
});
batchDeltaWeights.forEach((deltaWeights: Weights) => {
deltaWeights.forEach(
(layer: { weights: Weight[]; bias: Bias }[], l: number) => {
layer.forEach(
(neuron: { weights: Weight[]; bias: Bias }, n: number) => {
this.weights[l][n].bias += neuron.bias / batchSize;
neuron.weights.forEach((deltaWeight: Weight, w: number) => {
this.weights[l][n].weights[w] += deltaWeight / batchSize;
});
}
);
}
);
});
}
propagate(input: Layer): Layer[] {
let previousLayer: Layer = input;
const initialNeuron: Neuron = {
dotProduct: undefined,
activation: undefined,
};
let hiddenLayers = this.layers
.slice(1)
.map((l): Layer => Array(l).fill(initialNeuron));
hiddenLayers = hiddenLayers.map((layer: Layer, l: number): Layer => {
const newLayer = layer.map((neuron: Neuron, n: number) => {
const dotProduct = this.dotProduct(this.weights[l][n], previousLayer);
const activation = this.activation.primitive(dotProduct);
return { ...neuron, activation, dotProduct };
});
previousLayer = newLayer;
return newLayer;
});
return [input, ...hiddenLayers];
}
backpropagate(
propagatedNetwork: Layer[],
label: Label,
learningRate: number,
momentum: number
): Weights {
let previousSensitivities: number[] = [];
const oldWeights: Weights = this.deepClone(this.weights);
const newDeltaWeights: Weights = this.getInitialWeights({ fixedWeight: 0 });
for (let l = propagatedNetwork.length - 1; l >= 1; l--) {
const isOutputLayer = l == propagatedNetwork.length - 1;
const layer = propagatedNetwork[l];
const previousLayer = propagatedNetwork[l - 1];
let sensitivities: number[] = [];
for (let n = 0; n < layer.length; n++) {
const neuron = layer[n];
const derivedActivation = this.activation.derivative(neuron.dotProduct);
let derivedError;
if (isOutputLayer) {
derivedError = this.derivedError(neuron.activation, label[n]);
} else {
const weightsFromNeuron = oldWeights[l].reduce((p, m) => {
return [...p, m.weights[n]];
}, []);
derivedError = previousSensitivities.reduce((p, s, i) => {
return p + s * weightsFromNeuron[i];
}, 0);
}
let sensitivity = derivedError * derivedActivation;
sensitivities.push(sensitivity);
const weightsToNeuron = oldWeights[l - 1][n].weights;
const previousBiasDeltaWeight =
this.previousDeltaWeights[l - 1][n].bias;
const newBiasDeltaWeight =
-learningRate * sensitivity + momentum * previousBiasDeltaWeight;
newDeltaWeights[l - 1][n].bias = newBiasDeltaWeight;
for (let w = 0; w < weightsToNeuron.length; w++) {
const { activation: leftConnectedActivation } = previousLayer[w];
const previousDeltaWeight =
this.previousDeltaWeights[l - 1][n].weights[w];
const newDeltaWeight =
-learningRate * sensitivity * leftConnectedActivation +
momentum * previousDeltaWeight;
this.previousDeltaWeights[l - 1][n].weights[w] = newDeltaWeight;
newDeltaWeights[l - 1][n].weights[w] = newDeltaWeight;
}
}
previousSensitivities = sensitivities;
sensitivities = [];
}
return newDeltaWeights;
}
calculateError(output: Layer, label: Label) {
if (output.length !== label.length) {
throw new Error("conflict at calculating error");
}
const outputActivations = output.map((o) => o.activation);
const numberOfOutputs = output.length;
let squaredErrorSum = 0;
for (let o = 0; o < numberOfOutputs; o++) {
squaredErrorSum += this.halfSquaredError(outputActivations[o], label[o]);
}
return squaredErrorSum / numberOfOutputs;
}
halfSquaredError(real: number, desired: number): number {
return 0.5 * Math.pow(real - desired, 2);
}
derivedError(real: number, desired: number): number {
return real - desired;
}
dotProduct(
{ weights, bias }: { weights: Weight[]; bias: Bias },
previousLayer: Layer
) {
if (weights.length !== previousLayer.length) {
throw new Error("conflict at calculating next neuron value");
}
const numberOfWeights = weights.length;
let dotProductSum = bias;
for (let w = 0; w < numberOfWeights; w++) {
dotProductSum += weights[w] * previousLayer[w].activation;
}
return dotProductSum;
}
logAllValues(propagatedNetwork: Layer[], label: Label) {
let log = "\n\n- - - - - - - - - - -\nneuron activation values:\n";
let i = 0;
while (true) {
let continueAdding: Boolean = false;
propagatedNetwork.forEach((l: Layer) => {
const neuron = l[i];
log =
log +
(neuron ? Math.round(neuron.activation * 100) / 100 : " ") +
" ";
continueAdding = continueAdding || !!neuron;
});
if (!continueAdding) break;
log += "\n";
i += 1;
}
console.log(log);
const outputLayer = propagatedNetwork[propagatedNetwork.length - 1];
const error = this.calculateError(outputLayer, label);
console.log(
"output: " +
outputLayer.map((o) => Math.round(o.activation * 1000) / 1000) +
", \nlabel: " +
label +
", \nerror: " +
Math.round(error * 1000) / 1000 +
"\n- - - - - - - - - - -\n\n"
);
}
deepClone(object: Object) {
return JSON.parse(JSON.stringify(object));
}
weightFileExists(weightFile: string): Boolean {
const path = "weights/" + weightFile + ".json";
return existsSync(path);
}
readWeightFile(weightFile: string) {
const path = "weights/" + weightFile + ".json";
const weightFileContent = readFileSync(path, { encoding: "utf8" });
return JSON.parse(weightFileContent);
}
hasIdenticalDimensions(layers: number[]) {
return (
layers.length === this.layers.length &&
layers.every((l, i) => {
return l === this.layers[i];
})
);
}
writeWeightsToFile(weightFile: string) {
if (weightFile || this.weightFile) {
const path = "weights/" + (weightFile || this.weightFile) + ".json";
const content = { layers: this.layers, weights: this.weights };
writeFileSync(path, JSON.stringify(content));
}
}
getInitialWeights(weightOptions?: WeightOptions): Weights {
const {
weightFile,
fixedWeights,
fixedWeight,
lower,
higher,
biasLower,
biasHigher,
} = weightOptions || {};
this.weightFile = weightFile;
let initialWeights;
if (weightFile && this.weightFileExists(weightFile)) {
const { layers, weights } = this.readWeightFile(weightFile);
if (this.hasIdenticalDimensions(layers)) {
initialWeights = weights;
} else {
initialWeights = this.getRandomWeights({
lower,
higher,
biasLower,
biasHigher,
});
}
} else if (fixedWeights) {
initialWeights = fixedWeights;
} else if (typeof fixedWeight !== "undefined") {
initialWeights = this.getRandomWeights({ fixedWeight });
} else {
initialWeights = this.getRandomWeights({
lower,
higher,
biasLower,
biasHigher,
});
}
return initialWeights;
}
getRandomWeights(weightOptions: WeightOptions): Weights {
const { fixedWeight, lower, higher, biasLower, biasHigher } = weightOptions;
if (
lower >= higher ||
(typeof lower !== "undefined" && typeof higher === "undefined")
) {
throw new Error("cant initialize normal weights");
}
if (
biasLower >= biasHigher ||
(typeof biasLower !== "undefined" && typeof biasHigher === "undefined")
) {
throw new Error("cant initialize bias weights");
}
const layerDimensions = this.layers.reduce(
(p, l, i) => (this.layers[i + 1] ? [...p, [l, this.layers[i + 1]]] : p),
[]
);
const initialWeights: Weights = [];
layerDimensions.forEach(([neurons, weights]) => {
const weightsForLayers: { weights: Weight[]; bias: Bias }[] = [];
for (let w = 0; w < weights; w++) {
const bias: Bias =
typeof fixedWeight !== "undefined"
? fixedWeight
: Math.random() * ((biasHigher || 1) - (biasLower || 0)) +
(biasLower || 0);
const weightsToNeuron: { weights: Weight[]; bias: Bias } = {
weights: [],
bias,
};
for (let n = 0; n < neurons; n++) {
const randomWeight =
typeof fixedWeight !== "undefined"
? fixedWeight
: Math.random() * ((higher || 1) - (lower || 0)) + (lower || 0);
weightsToNeuron.weights.push(randomWeight);
}
weightsForLayers.push(weightsToNeuron);
}
initialWeights.push(weightsForLayers);
});
return initialWeights;
}
beautifyWeights(weights: Weights) {
return weights.map((l) => {
return l.map((n) => {
return {
weights: n.weights.map((w) => {
return Math.round(w * 100) / 100;
}),
bias: Math.round(n.bias * 100) / 100,
};
});
});
}
}