mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2026-03-13 08:51:02 +08:00
Add Euclidean Distance algorithm.
This commit is contained in:
@@ -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', () => {
|
||||
|
||||
@@ -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],
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user