Add Euclidean Distance algorithm.

This commit is contained in:
Oleksii Trekhleb
2020-12-19 19:21:32 +01:00
parent 59666ac947
commit 610f16fe20
7 changed files with 97 additions and 26 deletions

View File

@@ -25,7 +25,7 @@ describe('kNN', () => {
const inconsistent = () => {
kNN([[1, 1]], [1], [1]);
};
expect(inconsistent).toThrowError('Inconsistent vector lengths');
expect(inconsistent).toThrowError('Matrices have different shapes');
});
it('should find the nearest neighbour', () => {

View File

@@ -1,23 +1,3 @@
/**
* Calculates calculate the euclidean distance between 2 vectors.
*
* @param {number[]} x1
* @param {number[]} x2
* @returns {number}
*/
function euclideanDistance(x1, x2) {
// Checking for errors.
if (x1.length !== x2.length) {
throw new Error('Inconsistent vector lengths');
}
// Calculate the euclidean distance between 2 vectors and return.
let squaresTotal = 0;
for (let i = 0; i < x1.length; i += 1) {
squaresTotal += (x1[i] - x2[i]) ** 2;
}
return Number(Math.sqrt(squaresTotal).toFixed(2));
}
/**
* Classifies the point in space based on k-nearest neighbors algorithm.
*
@@ -27,6 +7,9 @@ function euclideanDistance(x1, x2) {
* @param {number} k - number of nearest neighbors which will be taken into account (preferably odd)
* @return {number} - the class of the point
*/
import euclideanDistance from '../../math/euclidean-distance/euclideanDistance';
export default function kNN(
dataSet,
labels,
@@ -42,7 +25,7 @@ export default function kNN(
const distances = [];
for (let i = 0; i < dataSet.length; i += 1) {
distances.push({
dist: euclideanDistance(dataSet[i], toClassify),
dist: euclideanDistance([dataSet[i]], [toClassify]),
label: labels[i],
});
}