-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathkn.html
More file actions
508 lines (437 loc) · 17.8 KB
/
kn.html
File metadata and controls
508 lines (437 loc) · 17.8 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
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>K-Nearest Neighbors Visualizer</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
margin: 0;
padding: 20px;
background-color: #f5f5f5;
color: #333;
}
.container {
max-width: 1000px;
margin: 0 auto;
}
h1 {
color: #2c3e50;
text-align: center;
margin-bottom: 30px;
}
.controls {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
margin-bottom: 20px;
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.control-group {
flex: 1;
min-width: 200px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input, select, button {
padding: 8px 12px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 16px;
width: 100%;
box-sizing: border-box;
}
button {
background-color: #3498db;
color: white;
border: none;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #2980b9;
}
button:disabled {
background-color: #95a5a6;
cursor: not-allowed;
}
.visualization {
display: flex;
flex-direction: column;
gap: 20px;
}
.plot-container {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
height: 500px;
position: relative;
}
#plotCanvas {
border: 1px solid #ddd;
background-color: white;
width: 100%;
height: 100%;
}
.legend {
display: flex;
justify-content: center;
gap: 20px;
margin-top: 15px;
flex-wrap: wrap;
}
.legend-item {
display: flex;
align-items: center;
gap: 5px;
font-size: 14px;
}
.legend-color {
width: 20px;
height: 20px;
border-radius: 50%;
border: 1px solid #333;
}
.step-info {
margin-top: 20px;
padding: 15px;
background-color: #f8f9fa;
border-radius: 4px;
border-left: 4px solid #3498db;
}
.explanation {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
line-height: 1.6;
}
.data-point {
position: absolute;
width: 12px;
height: 12px;
border-radius: 50%;
transform: translate(-6px, -6px);
border: 1px solid #333;
}
</style>
</head>
<body>
<div class="container">
<h1>K-Nearest Neighbors Visualizer</h1>
<div class="controls">
<div class="control-group">
<label for="kValue">Number of Neighbors (k):</label>
<input type="number" id="kValue" min="1" max="20" value="3">
</div>
<div class="control-group">
<label for="distanceMetric">Distance Metric:</label>
<select id="distanceMetric">
<option value="euclidean">Euclidean</option>
<option value="manhattan">Manhattan</option>
</select>
</div>
<div class="control-group">
<label for="classCount">Number of Classes:</label>
<select id="classCount">
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<div class="control-group">
<label for="showDecision">Show Decision Boundary:</label>
<select id="showDecision">
<option value="true">Yes</option>
<option value="false">No</option>
</select>
</div>
<div class="control-group">
<label> </label>
<button id="generateDataBtn">Generate New Data</button>
<button id="resetBtn">Reset</button>
</div>
</div>
<div class="visualization">
<div class="plot-container">
<canvas id="plotCanvas"></canvas>
<div id="dataPoints"></div>
</div>
<div class="legend">
<div class="legend-item">
<div class="legend-color" style="background-color: #e74c3c;"></div>
<span>Class 1</span>
</div>
<div class="legend-item">
<div class="legend-color" style="background-color: #3498db;"></div>
<span>Class 2</span>
</div>
<div class="legend-item" id="class3Legend" style="display: none;">
<div class="legend-color" style="background-color: #2ecc71;"></div>
<span>Class 3</span>
</div>
<div class="legend-item" id="class4Legend" style="display: none;">
<div class="legend-color" style="background-color: #9b59b6;"></div>
<span>Class 4</span>
</div>
<div class="legend-item">
<div class="legend-color" style="background-color: #f1c40f;"></div>
<span>Test Point</span>
</div>
</div>
<div class="step-info" id="stepInfo">
Click on the plot to add a test point and see KNN classification.
</div>
</div>
<div class="explanation">
<h2>How K-Nearest Neighbors Works</h2>
<p>K-Nearest Neighbors (KNN) is a simple, instance-based learning algorithm that classifies new data points based on their similarity to existing data points.</p>
<h3>Algorithm Steps:</h3>
<ol>
<li>Store all training data points</li>
<li>When classifying a new point:
<ol>
<li>Calculate distances to all stored points</li>
<li>Select the k nearest points</li>
<li>Assign the most common class among these neighbors</li>
</ol>
</li>
</ol>
<h3>Key Parameters:</h3>
<ul>
<li><strong>k</strong>: Number of neighbors to consider (small k = more complex boundaries)</li>
<li><strong>Distance Metric</strong>: How to measure similarity between points</li>
</ul>
<h3>Characteristics:</h3>
<ul>
<li>No explicit training phase (lazy learning)</li>
<li>Decision boundaries can be highly non-linear</li>
<li>Sensitive to the choice of k and distance metric</li>
<li>Works well for small to medium datasets</li>
</ul>
</div>
</div>
<script>
// DOM Elements
const kValueInput = document.getElementById('kValue');
const distanceMetricSelect = document.getElementById('distanceMetric');
const classCountSelect = document.getElementById('classCount');
const showDecisionSelect = document.getElementById('showDecision');
const generateDataBtn = document.getElementById('generateDataBtn');
const resetBtn = document.getElementById('resetBtn');
const plotCanvas = document.getElementById('plotCanvas');
const dataPointsContainer = document.getElementById('dataPoints');
const stepInfo = document.getElementById('stepInfo');
const class3Legend = document.getElementById('class3Legend');
const class4Legend = document.getElementById('class4Legend');
// Canvas setup
const ctx = plotCanvas.getContext('2d');
plotCanvas.width = plotCanvas.offsetWidth;
plotCanvas.height = plotCanvas.offsetHeight;
// Colors for classes
const classColors = [
'#e74c3c', // Class 1 (red)
'#3498db', // Class 2 (blue)
'#2ecc71', // Class 3 (green)
'#9b59b6' // Class 4 (purple)
];
const testPointColor = '#f1c40f'; // Yellow
// Data and state
let data = [];
let testPoint = null;
let classCount = 2;
// Initialize
generateData();
// Event listeners
generateDataBtn.addEventListener('click', generateData);
resetBtn.addEventListener('click', reset);
plotCanvas.addEventListener('click', handleCanvasClick);
classCountSelect.addEventListener('change', updateClassVisibility);
kValueInput.addEventListener('input', redraw);
distanceMetricSelect.addEventListener('change', redraw);
showDecisionSelect.addEventListener('change', redraw);
// Generate random training data
function generateData() {
classCount = parseInt(classCountSelect.value);
updateClassVisibility();
data = [];
const clusterCenters = [];
const clusterSpread = 0.15;
// Generate cluster centers
for (let i = 0; i < classCount; i++) {
clusterCenters.push({
x: 0.2 + Math.random() * 0.6,
y: 0.2 + Math.random() * 0.6
});
}
// Generate points around each center
const pointsPerClass = 50;
for (let classIdx = 0; classIdx < classCount; classIdx++) {
for (let i = 0; i < pointsPerClass; i++) {
data.push({
x: clusterCenters[classIdx].x + (Math.random() - 0.5) * clusterSpread,
y: clusterCenters[classIdx].y + (Math.random() - 0.5) * clusterSpread,
class: classIdx
});
}
}
testPoint = null;
redraw();
}
// Update class visibility in legend
function updateClassVisibility() {
class3Legend.style.display = classCount >= 3 ? 'flex' : 'none';
class4Legend.style.display = classCount >= 4 ? 'flex' : 'none';
}
// Reset visualization
function reset() {
testPoint = null;
redraw();
stepInfo.textContent = "Click on the plot to add a test point and see KNN classification.";
}
// Handle canvas clicks
function handleCanvasClick(event) {
const rect = plotCanvas.getBoundingClientRect();
const x = (event.clientX - rect.left) / plotCanvas.width;
const y = (event.clientY - rect.top) / plotCanvas.height;
testPoint = { x, y };
classifyPoint(testPoint);
redraw();
}
// Classify a point using KNN
function classifyPoint(point) {
const k = parseInt(kValueInput.value);
const distanceMetric = distanceMetricSelect.value;
// Calculate distances to all points
const distances = data.map(dataPoint => ({
point: dataPoint,
distance: calculateDistance(point, dataPoint, distanceMetric)
}));
// Sort by distance
distances.sort((a, b) => a.distance - b.distance);
// Get k nearest neighbors
const neighbors = distances.slice(0, k);
// Count class occurrences
const classCounts = new Array(classCount).fill(0);
neighbors.forEach(neighbor => {
classCounts[neighbor.point.class]++;
});
// Find majority class
const maxCount = Math.max(...classCounts);
const predictedClass = classCounts.indexOf(maxCount);
// Update step info
stepInfo.innerHTML = `
<strong>Classification Result:</strong><br>
- Test point at (${point.x.toFixed(2)}, ${point.y.toFixed(2)})<br>
- Using k = ${k} and ${distanceMetric} distance<br>
- Nearest neighbors: ${neighbors.map(n => `Class ${n.point.class + 1}`).join(', ')}<br>
- Predicted class: <strong>Class ${predictedClass + 1}</strong>
`;
return predictedClass;
}
// Calculate distance between two points
function calculateDistance(p1, p2, metric) {
const dx = p1.x - p2.x;
const dy = p1.y - p2.y;
switch (metric) {
case 'euclidean':
return Math.sqrt(dx * dx + dy * dy);
case 'manhattan':
return Math.abs(dx) + Math.abs(dy);
default:
return Math.sqrt(dx * dx + dy * dy);
}
}
// Redraw the entire visualization
function redraw() {
// Clear canvas
ctx.clearRect(0, 0, plotCanvas.width, plotCanvas.height);
// Draw decision boundary if enabled
if (showDecisionSelect.value === 'true') {
drawDecisionBoundary();
}
// Draw data points
drawDataPoints();
// Draw test point if exists
if (testPoint) {
drawTestPoint();
}
}
// Draw decision boundary
function drawDecisionBoundary() {
const resolution = 20; // How many points to sample in each dimension
const k = parseInt(kValueInput.value);
const distanceMetric = distanceMetricSelect.value;
const cellWidth = plotCanvas.width / resolution;
const cellHeight = plotCanvas.height / resolution;
for (let i = 0; i < resolution; i++) {
for (let j = 0; j < resolution; j++) {
const x = (i + 0.5) / resolution;
const y = (j + 0.5) / resolution;
// Classify this grid point
const distances = data.map(dataPoint => ({
point: dataPoint,
distance: calculateDistance({x, y}, dataPoint, distanceMetric)
}));
distances.sort((a, b) => a.distance - b.distance);
const neighbors = distances.slice(0, k);
const classCounts = new Array(classCount).fill(0);
neighbors.forEach(neighbor => {
classCounts[neighbor.point.class]++;
});
const maxCount = Math.max(...classCounts);
const predictedClass = classCounts.indexOf(maxCount);
// Draw the cell with class color (lighter shade)
ctx.fillStyle = lightenColor(classColors[predictedClass], 0.7);
ctx.fillRect(
i * cellWidth,
j * cellHeight,
cellWidth,
cellHeight
);
}
}
}
// Draw all data points
function drawDataPoints() {
dataPointsContainer.innerHTML = '';
data.forEach(point => {
const elem = document.createElement('div');
elem.className = 'data-point';
elem.style.backgroundColor = classColors[point.class];
elem.style.left = `${point.x * 100}%`;
elem.style.top = `${point.y * 100}%`;
dataPointsContainer.appendChild(elem);
});
}
// Draw the test point
function drawTestPoint() {
const elem = document.createElement('div');
elem.className = 'data-point';
elem.style.backgroundColor = testPointColor;
elem.style.width = '16px';
elem.style.height = '16px';
elem.style.transform = 'translate(-8px, -8px)';
elem.style.left = `${testPoint.x * 100}%`;
elem.style.top = `${testPoint.y * 100}%`;
dataPointsContainer.appendChild(elem);
}
// Lighten a color
function lightenColor(color, amount) {
const num = parseInt(color.replace('#', ''), 16);
const r = Math.min(255, (num >> 16) + 255 * amount);
const g = Math.min(255, (num >> 8 & 0x00FF) + 255 * amount);
const b = Math.min(255, (num & 0x0000FF) + 255 * amount);
return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;
}
</script>
</body>
</html>