|
| 1 | +import unittest |
| 2 | +from unittest.mock import patch |
| 3 | + |
| 4 | +import numpy as np |
| 5 | +from scipy import sparse |
| 6 | +import sklearn |
| 7 | + |
| 8 | +from Orange.data import Table |
| 9 | +from Orange.modelling import KNNLearner |
| 10 | + |
| 11 | +knn_init = sklearn.neighbors.KNeighborsClassifier.__init__ |
| 12 | + |
| 13 | + |
| 14 | +class Test(unittest.TestCase): |
| 15 | + def setUp(self): |
| 16 | + x = np.array([[3, 0, 4], |
| 17 | + [12, 5, 0], |
| 18 | + [1, 2, 2]]) |
| 19 | + y = np.array([1, 0, 1]) |
| 20 | + self.data = Table.from_numpy(None, x, y) |
| 21 | + |
| 22 | + @patch("Orange.base.SklLearner.fit") |
| 23 | + def test_cosine_normalizes(self, fit): |
| 24 | + learner = KNNLearner(metric="cosine") |
| 25 | + learner(self.data) |
| 26 | + X = fit.call_args[0][0] |
| 27 | + np.testing.assert_allclose(np.sum(X ** 2, axis=1), 1) |
| 28 | + np.testing.assert_allclose(X, [ |
| 29 | + [3 / 5, 0, 4 / 5], |
| 30 | + [12 / 13, 5 / 13, 0], |
| 31 | + [1 / 3, 2 / 3, 2 / 3]]) |
| 32 | + fit.reset_mock() |
| 33 | + |
| 34 | + with self.data.unlocked(): |
| 35 | + self.data.X = sparse.csr_matrix(self.data.X) |
| 36 | + learner(self.data) |
| 37 | + X = fit.call_args[0][0] |
| 38 | + np.testing.assert_allclose(np.sum(X ** 2, axis=1), 1) |
| 39 | + row0 = X[0] |
| 40 | + np.testing.assert_allclose(row0, row0 / np.linalg.norm(row0)) |
| 41 | + |
| 42 | + def test_cosine_does_not_modify_input_data(self): |
| 43 | + original = self.data.X.copy() |
| 44 | + learner = KNNLearner(metric="cosine") |
| 45 | + learner(self.data) |
| 46 | + np.testing.assert_array_equal(self.data.X, original) |
| 47 | + |
| 48 | + @patch("sklearn.neighbors.KNeighborsClassifier.__init__", |
| 49 | + side_effect=knn_init, autospec=True) |
| 50 | + def test_cosine_computes_euclidean(self, mock_init): |
| 51 | + learner = KNNLearner(metric="cosine") |
| 52 | + learner(self.data) |
| 53 | + self.assertEqual(mock_init.call_args[1]["metric"], "euclidean") |
| 54 | + |
| 55 | + learner = KNNLearner(metric="manhattan") |
| 56 | + learner(self.data) |
| 57 | + self.assertEqual(mock_init.call_args[1]["metric"], "manhattan") |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == "__main__": |
| 61 | + unittest.main() |
0 commit comments