|
| 1 | +import kNN from '../kNN'; |
| 2 | + |
| 3 | +describe('kNN', () => { |
| 4 | + it('should throw an error on invalid data', () => { |
| 5 | + expect(() => { |
| 6 | + kNN(); |
| 7 | + }).toThrowError('Either dataSet or labels or toClassify were not set'); |
| 8 | + }); |
| 9 | + |
| 10 | + it('should throw an error on invalid labels', () => { |
| 11 | + const noLabels = () => { |
| 12 | + kNN([[1, 1]]); |
| 13 | + }; |
| 14 | + expect(noLabels).toThrowError('Either dataSet or labels or toClassify were not set'); |
| 15 | + }); |
| 16 | + |
| 17 | + it('should throw an error on not giving classification vector', () => { |
| 18 | + const noClassification = () => { |
| 19 | + kNN([[1, 1]], [1]); |
| 20 | + }; |
| 21 | + expect(noClassification).toThrowError('Either dataSet or labels or toClassify were not set'); |
| 22 | + }); |
| 23 | + |
| 24 | + it('should throw an error on not giving classification vector', () => { |
| 25 | + const inconsistent = () => { |
| 26 | + kNN([[1, 1]], [1], [1]); |
| 27 | + }; |
| 28 | + expect(inconsistent).toThrowError('Inconsistent vector lengths'); |
| 29 | + }); |
| 30 | + |
| 31 | + it('should find the nearest neighbour', () => { |
| 32 | + let dataSet; |
| 33 | + let labels; |
| 34 | + let toClassify; |
| 35 | + let expectedClass; |
| 36 | + |
| 37 | + dataSet = [[1, 1], [2, 2]]; |
| 38 | + labels = [1, 2]; |
| 39 | + toClassify = [1, 1]; |
| 40 | + expectedClass = 1; |
| 41 | + expect(kNN(dataSet, labels, toClassify)).toBe(expectedClass); |
| 42 | + |
| 43 | + dataSet = [[1, 1], [6, 2], [3, 3], [4, 5], [9, 2], [2, 4], [8, 7]]; |
| 44 | + labels = [1, 2, 1, 2, 1, 2, 1]; |
| 45 | + toClassify = [1.25, 1.25]; |
| 46 | + expectedClass = 1; |
| 47 | + expect(kNN(dataSet, labels, toClassify)).toBe(expectedClass); |
| 48 | + |
| 49 | + dataSet = [[1, 1], [6, 2], [3, 3], [4, 5], [9, 2], [2, 4], [8, 7]]; |
| 50 | + labels = [1, 2, 1, 2, 1, 2, 1]; |
| 51 | + toClassify = [1.25, 1.25]; |
| 52 | + expectedClass = 2; |
| 53 | + expect(kNN(dataSet, labels, toClassify, 5)).toBe(expectedClass); |
| 54 | + }); |
| 55 | + |
| 56 | + it('should find the nearest neighbour with equal distances', () => { |
| 57 | + const dataSet = [[0, 0], [1, 1], [0, 2]]; |
| 58 | + const labels = [1, 3, 3]; |
| 59 | + const toClassify = [0, 1]; |
| 60 | + const expectedClass = 3; |
| 61 | + expect(kNN(dataSet, labels, toClassify)).toBe(expectedClass); |
| 62 | + }); |
| 63 | + |
| 64 | + it('should find the nearest neighbour in 3D space', () => { |
| 65 | + const dataSet = [[0, 0, 0], [0, 1, 1], [0, 0, 2]]; |
| 66 | + const labels = [1, 3, 3]; |
| 67 | + const toClassify = [0, 0, 1]; |
| 68 | + const expectedClass = 3; |
| 69 | + expect(kNN(dataSet, labels, toClassify)).toBe(expectedClass); |
| 70 | + }); |
| 71 | +}); |
0 commit comments