File size: 1,924 Bytes
f7c7e26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
let points = [
  [2, 3, 0], [3, 4, 0], [1, 1, 0], 
  [7, 8, 1], [6, 9, 1], [8, 7, 1]
]; // (x, y, label)
let testPoint = [4.5, 5.5];

const ctx = document.getElementById('knnChart').getContext('2d');
const colors = ['#1f77b4', '#ff7f0e', '#2ca02c'];

let chart = new Chart(ctx, {
  type: 'scatter',
  data: {
    datasets: [
      {
        label: 'Class 0',
        data: points.filter(p => p[2] === 0).map(p => ({ x: p[0], y: p[1] })),
        backgroundColor: colors[0]
      },
      {
        label: 'Class 1',
        data: points.filter(p => p[2] === 1).map(p => ({ x: p[0], y: p[1] })),
        backgroundColor: colors[1]
      },
      {
        label: 'Test Point',
        data: [{ x: testPoint[0], y: testPoint[1] }],
        backgroundColor: 'black',
        pointStyle: 'triangle',
        radius: 7
      }
    ]
  },
  options: {
    responsive: true,
    plugins: {
      legend: { position: 'top' },
      title: { display: true, text: 'KNN Classification Plot' }
    },
    scales: {
      x: { type: 'linear', position: 'bottom' },
      y: { type: 'linear' }
    }
  }
});

async function sendToServer() {
  const k = document.getElementById('k-value').value;

  const response = await fetch('/knn_visual_predict', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ points, test_point: testPoint, k })
  });

  const result = await response.json();

  document.getElementById('output').innerHTML =
    `Prediction: <strong>Class ${result.prediction}</strong>`;

  // Highlight neighbors
  const neighborLayer = {
    label: 'Nearest Neighbors',
    data: result.neighbors.map(p => ({ x: p[0], y: p[1] })),
    backgroundColor: '#d62728',
    pointStyle: 'rect',
    radius: 6
  };

  chart.data.datasets = chart.data.datasets.slice(0, 3).concat([neighborLayer]);
  chart.update();
}