-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
298 lines (248 loc) · 6.88 KB
/
script.js
File metadata and controls
298 lines (248 loc) · 6.88 KB
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
const mycanvas = document.getElementById("canvas");
const ctx = mycanvas.getContext("2d");
const slider = document.getElementById("myRange");
const output = document.getElementById("sliderValue");
const enter = document.getElementById("enter");
const pred = document.getElementById("prediction");
if (window.innerWidth <= 600) {
mycanvas.height = 300;
mycanvas.width = 300;
} else {
mycanvas.height = 450;
mycanvas.width = 450;
}
let drawing = false;
let posX = 0;
let posY = 0;
let strokewidth = 25;
ctx.fillStyle = "white";
ctx.fillRect(0, 0, mycanvas.width, mycanvas.height);
//Mouse Event listeners
mycanvas.addEventListener("mousedown", (e) => {
init(e);
drawing = true;
});
mycanvas.addEventListener("mouseup", () => {
drawing = false;
});
mycanvas.addEventListener("mousemove", (e) => {
if (drawing) draw(e.offsetX, e.offsetY);
});
//Touch event listeners
mycanvas.addEventListener("touchstart", (e) => {
initTouch(e);
drawing = true;
});
mycanvas.addEventListener("touchend", () => {
drawing = false;
});
mycanvas.addEventListener("touchmove", (e) => {
if (drawing) {
e.preventDefault(); // Prevent scrolling
const rect = mycanvas.getBoundingClientRect();
const x = e.touches[0].clientX - rect.left;
const y = e.touches[0].clientY - rect.top;
draw(x, y);
}
});
// Initialize for mouse
function init(e) {
posX = e.offsetX;
posY = e.offsetY;
}
// Initialize for touch
function initTouch(e) {
e.preventDefault();
const rect = mycanvas.getBoundingClientRect();
posX = e.touches[0].clientX - rect.left;
posY = e.touches[0].clientY - rect.top;
}
// Unified draw function for both mouse & touch
function draw(x, y) {
ctx.lineWidth = strokewidth;
ctx.lineJoin = "round";
ctx.lineCap = "round";
ctx.beginPath();
ctx.moveTo(posX, posY);
ctx.lineTo(x, y);
ctx.stroke();
ctx.closePath();
posX = x;
posY = y;
}
const clearbtn = document.getElementById("clear");
clearbtn.addEventListener("click", () => {
ctx.clearRect(0, 0, mycanvas.width, mycanvas.height);
ctx.fillStyle = "white";
ctx.fillRect(0, 0, mycanvas.width, mycanvas.height);
pred.textContent = "";
});
//slider
slider.oninput = function () {
output.textContent = this.value;
strokewidth = 20.0 + parseInt(this.value);
console.log(strokewidth);
};
//colour picker
colourpicker.addEventListener("change", (e) => {
ctx.strokeStyle = e.target.value;
});
//model
let model;
async function loadModel() {
try {
// Create the model architecture to match your JSON exactly
model = tf.sequential();
// Input layer - explicit shape
model.add(
tf.layers.inputLayer({
inputShape: [28, 28, 1],
name: "input_layer",
})
);
// First Conv2D layer
model.add(
tf.layers.conv2d({
filters: 32,
kernelSize: [3, 3],
activation: "relu",
name: "conv2d",
})
);
// First MaxPooling layer
model.add(
tf.layers.maxPooling2d({
poolSize: [2, 2],
strides: [2, 2],
name: "max_pooling2d",
})
);
// Second Conv2D layer
model.add(
tf.layers.conv2d({
filters: 48,
kernelSize: [3, 3],
activation: "relu",
name: "conv2d_1",
})
);
// Second MaxPooling layer
model.add(
tf.layers.maxPooling2d({
poolSize: [2, 2],
strides: [2, 2],
name: "max_pooling2d_1",
})
);
// Dropout layer
model.add(
tf.layers.dropout({
rate: 0.5,
name: "dropout",
})
);
// Flatten layer
model.add(
tf.layers.flatten({
name: "flatten",
})
);
// First Dense layer
model.add(
tf.layers.dense({
units: 500,
activation: "relu",
name: "dense",
})
);
// Output layer
model.add(
tf.layers.dense({
units: 10,
activation: "softmax",
name: "dense_1",
})
);
// Load weights
const weightsResponse = await fetch("model/group1-shard1of1.bin");
const weightsBuffer = await weightsResponse.arrayBuffer();
const weightsArray = new Float32Array(weightsBuffer);
// Set weights in correct order
const weights = [];
let offset = 0;
// Weight shapes in order of layers
const weightShapes = [
[3, 3, 1, 32], // conv2d kernel
[32], // conv2d bias
[3, 3, 32, 48], // conv2d_1 kernel
[48], // conv2d_1 bias
[1200, 500], // dense kernel (28x28 -> maxpool(13x13) -> maxpool(5x5) -> 5*5*48 = 1200)
[500], // dense bias
[500, 10], // dense_1 kernel
[10], // dense_1 bias
];
for (const shape of weightShapes) {
const size = shape.reduce((a, b) => a * b, 1);
const values = weightsArray.slice(offset, offset + size);
offset += size;
weights.push(tf.tensor(values, shape));
}
model.setWeights(weights);
// Compile the model (not necessary for inference but good practice)
model.compile({
optimizer: tf.train.adam(0.001),
loss: "sparseCategoricalCrossentropy",
metrics: ["accuracy"],
});
console.log("Model loaded successfully!");
model.summary();
} catch (err) {
console.error("Error loading model:", err);
}
}
loadModel();
// FIXED PREDICTION FUNCTION
enter.addEventListener("click", async () => {
if (!model) {
alert("Model is still loading. Please try again in a moment.");
return;
}
try {
// Create a temporary canvas for processing
const tempCanvas = document.createElement("canvas");
tempCanvas.width = 28;
tempCanvas.height = 28;
const tctx = tempCanvas.getContext("2d");
// Fill background to white
tctx.fillStyle = "white";
tctx.fillRect(0, 0, tempCanvas.width, tempCanvas.height);
// Draw and scale to 28x28
tctx.drawImage(mycanvas, 0, 0, 28, 28);
// Get image data
const imageData = tctx.getImageData(0, 0, 28, 28);
const data = imageData.data;
// Convert to grayscale and normalize
const inputData = new Float32Array(28 * 28 * 1);
for (let i = 0; i < data.length; i += 4) {
// Convert to grayscale (luminance method)
const gray = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
// Normalize to 0-1 and invert (MNIST style - white on black)
inputData[i / 4] = (255 - gray) / 255.0;
}
// Create tensor for prediction
const inputTensor = tf.tensor4d(inputData, [1, 28, 28, 1]);
// Make prediction
const prediction = model.predict(inputTensor);
const results = await prediction.data();
// Get the predicted digit
const predictedDigit = results.indexOf(Math.max(...results));
console.log(`Predicted digit: ${predictedDigit}`);
pred.textContent = "Predicted Number: " + predictedDigit;
// Clean up
inputTensor.dispose();
prediction.dispose();
} catch (err) {
console.error("Prediction error:", err);
alert("Error making prediction. See console for details.");
}
});