def test_radius_neighbors(self): """Test query with radius""" nn = NearestNeighbors(radius=.1) nn.fit(self.X) knn = RadiusNeighborsClassifier(radius=.1) knn.fit(self.X, self.y) knnr = RadiusNeighborsRegressor(radius=.1) knnr.fit(self.X, self.modes_location) for neigh in [nn, knn, knnr]: dist, links = neigh.radius_neighbors(self.X[:4]) np.testing.assert_array_equal(links[0], np.array([0, 7])) np.testing.assert_array_equal(links[1], np.array([1])) np.testing.assert_array_equal(links[2], np.array([2, 17, 22, 27])) np.testing.assert_array_equal(links[3], np.array([3, 4, 9])) dist_kneigh = lp_distance(self.X[0], self.X[7]) np.testing.assert_array_almost_equal(dist[0][1], dist_kneigh) graph = neigh.radius_neighbors_graph(self.X[:4]) for i in range(30): self.assertEqual(graph[0, i] == 1.0, i in links[0]) self.assertEqual(graph[0, i] == 0.0, i not in links[0])
def test_multivariate_response_score(self): neigh = RadiusNeighborsRegressor() y = make_multimodal_samples(n_samples=5, dim_domain=2, random_state=0) neigh.fit(self.X[:5], y) # It is not supported the multivariate score by the moment with np.testing.assert_raises(ValueError): neigh.score(self.X[:5], y)
def test_radius_functional_response(self): knnr = RadiusNeighborsRegressor(metric=lp_distance, weights='distance', regressor=l2_mean) knnr.fit(self.X, self.X) res = knnr.predict(self.X) np.testing.assert_array_almost_equal(res.data_matrix, self.X.data_matrix)
def test_predict_regressor(self): """Test scalar regression, predics mode location""" # Dummy test, with weight = distance, only the sample with distance 0 # will be returned, obtaining the exact location knnr = KNeighborsRegressor(weights='distance') rnnr = RadiusNeighborsRegressor(weights='distance', radius=.1) knnr.fit(self.X, self.modes_location) rnnr.fit(self.X, self.modes_location) np.testing.assert_array_almost_equal(knnr.predict(self.X), self.modes_location) np.testing.assert_array_almost_equal(rnnr.predict(self.X), self.modes_location)
def test_radius_outlier_functional_response(self): knnr = RadiusNeighborsRegressor(radius=0.001) knnr.fit(self.X[3:6], self.X[3:6]) # No value given with np.testing.assert_raises(ValueError): knnr.predict(self.X[:10]) # Test response knnr = RadiusNeighborsRegressor(radius=0.001, outlier_response=self.X[0]) knnr.fit(self.X[:6], self.X[:6]) res = knnr.predict(self.X[:7]) np.testing.assert_array_almost_equal(self.X[0].data_matrix, res[6].data_matrix)
def test_score_functional_response_exceptions(self): neigh = RadiusNeighborsRegressor() neigh.fit(self.X, self.X) with np.testing.assert_raises(ValueError): neigh.score(self.X, self.X, sample_weight=[1, 2, 3])
def test_functional_regressor_exceptions(self): knnr = RadiusNeighborsRegressor() with np.testing.assert_raises(ValueError): knnr.fit(self.X[:3], self.X[:4])