Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/algorithms/ml/knn/__test__/knn.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ describe('kNN', () => {
expect(inconsistent).toThrow('Matrices have different shapes');
});

it('should throw an error on mismatched dataSet and labels lengths', () => {
const mismatched = () => {
kNN([[1, 1], [2, 2]], [1], [1, 1]);
};
expect(mismatched).toThrow('The number of dataSet points must match the number of labels');
});

it('should find the nearest neighbour', () => {
let dataSet;
let labels;
Expand Down
4 changes: 4 additions & 0 deletions src/algorithms/ml/knn/kNN.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ export default function kNN(
throw new Error('Either dataSet or labels or toClassify were not set');
}

if (dataSet.length !== labels.length) {
throw new Error('The number of dataSet points must match the number of labels');
}

// Calculate distance from toClassify to each point for all dimensions in dataSet.
// Store distance and point's label into distances list.
const distances = [];
Expand Down