|
|
let points = [
|
|
|
[2, 3, 0], [3, 4, 0], [1, 1, 0],
|
|
|
[7, 8, 1], [6, 9, 1], [8, 7, 1]
|
|
|
];
|
|
|
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>`;
|
|
|
|
|
|
|
|
|
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();
|
|
|
} |