소개
이 랩에서는 데이터 포인트 분류에 강력한 도구인 K-최근접 이웃 (K-Nearest Neighbors, KNN) 알고리즘을 탐구합니다. JavaScript 로 이 알고리즘을 구현함으로써, 기존의 레이블된 데이터 포인트와의 근접성을 기반으로 새로운 데이터 포인트를 분류할 수 있으며, 이는 추천 시스템 및 이미지 인식과 같은 다양한 응용 분야에 유용한 도구가 됩니다. 이 랩을 통해 머신 러닝 알고리즘이 어떻게 작동하고 실제 시나리오에서 어떻게 구현될 수 있는지 더 깊이 이해하게 될 것입니다.
K-최근접 이웃 (K-Nearest Neighbors) 알고리즘
K-최근접 이웃 알고리즘을 사용하려면 다음 단계를 따르세요.
- 터미널/SSH 를 열고
node를 입력합니다. - k-최근접 이웃 알고리즘을 사용하여 레이블된 데이터 세트를 기준으로 데이터 포인트를 분류합니다.
Array.prototype.map()을 사용하여data를 객체에 매핑합니다. 각 객체는Math.hypot(),Object.keys()및 해당label을 사용하여 계산된,point에서 요소까지의 유클리드 거리 (Euclidean distance) 를 포함합니다.Array.prototype.sort()및Array.prototype.slice()를 사용하여point의k개의 가장 가까운 이웃을 가져옵니다.Array.prototype.reduce()를Object.keys()및Array.prototype.indexOf()와 함께 사용하여 가장 빈번한label을 찾습니다.
다음은 K-최근접 이웃 알고리즘을 구현하는 코드 예시입니다.
const kNearestNeighbors = (data, labels, point, k = 3) => {
const kNearest = data
.map((el, i) => ({
dist: Math.hypot(...Object.keys(el).map((key) => point[key] - el[key])),
label: labels[i]
}))
.sort((a, b) => a.dist - b.dist)
.slice(0, k);
return kNearest.reduce(
(acc, { label }, i) => {
acc.classCounts[label] =
Object.keys(acc.classCounts).indexOf(label) !== -1
? acc.classCounts[label] + 1
: 1;
if (acc.classCounts[label] > acc.topClassCount) {
acc.topClassCount = acc.classCounts[label];
acc.topClass = label;
}
return acc;
},
{
classCounts: {},
topClass: kNearest[0].label,
topClassCount: 0
}
).topClass;
};
다음은 코드를 사용하는 방법입니다.
const data = [
[0, 0],
[0, 1],
[1, 3],
[2, 0]
];
const labels = [0, 1, 1, 0];
kNearestNeighbors(data, labels, [1, 2], 2); // 1
kNearestNeighbors(data, labels, [1, 0], 2); // 0
요약
축하합니다! K-최근접 이웃 랩을 완료했습니다. LabEx 에서 더 많은 랩을 연습하여 실력을 향상시킬 수 있습니다.