1import * as tf from '@tensorflow/tfjs';
2
3// 1. Construct Browser Neural Network
4const model = tf.sequential({
5 layers: [
6 tf.layers.dense({ units: 6, activation: 'sigmoid', inputShape: [64] }),
7 tf.layers.dense({ units: 10, activation: 'softmax' })
8 ]
9});
10
11// 2. Compile Model with Hardware Acceleration (WebGL / WebGPU / CPU)
12model.compile({
13 optimizer: tf.train.sgd(0.005),
14 loss: 'categoricalCrossentropy',
15 metrics: ['accuracy']
16});
17
18// 3. Train in the Browser (35 Epochs)
19async function trainInBrowser(xTensor, yTensor, onEpochEnd) {
20 return await model.fit(xTensor, yTensor, {
21 epochs: 35,
22 batchSize: 16,
23 validationSplit: 0.15,
24 callbacks: {
25 onEpochEnd: (epoch, logs) => {
26 onEpochEnd({
27 epoch: epoch + 1,
28 loss: logs.loss,
29 acc: logs.acc,
30 valLoss: logs.val_loss,
31 valAcc: logs.val_acc
32 });
33 }
34 }
35 });
36}
37
38// 4. Real-time Inference on Drawn Pixels
39function predict(flatPixels) {
40 return tf.tidy(() => {
41 const input = tf.tensor2d([flatPixels], [1, 64]);
42 const probs = model.predict(input);
43 const data = probs.dataSync();
44 const bestIndex = probs.argMax(-1).dataSync()[0];
45 return { bestIndex, probabilities: Array.from(data) };
46 });
47}
48