Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ENH] Neighbours - Sort resulting instances in order according to distance #6425

Merged
merged 1 commit into from
Apr 28, 2023
Merged
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: 6 additions & 1 deletion Orange/widgets/data/owneighbors.py
Original file line number Diff line number Diff line change
@@ -153,7 +153,12 @@ def _compute_indices(self):
up_to = len(dist) - np.sum(inrefs)
if self.limit_neighbors and self.n_neighbors < up_to:
up_to = self.n_neighbors
return np.argpartition(dist, up_to - 1)[:up_to]
# get indexes of N neighbours in unsorted order - faster than argsort
idx = np.argpartition(dist, up_to - 1)[:up_to]
# sort selected N neighbours according to distances
sorted_subset_idx = np.argsort(dist[idx])
# map sorted indexes back to original index space
return idx[sorted_subset_idx]

def _data_with_similarity(self, indices):
domain = self.data.domain
19 changes: 19 additions & 0 deletions Orange/widgets/data/tests/test_owneighbors.py
Original file line number Diff line number Diff line change
@@ -452,6 +452,25 @@ class Table2(Table):
self.send_signal(self.widget.Inputs.reference, data[0:1])
self.assertIsInstance(self.get_output(self.widget.Outputs.data), Table2)

def test_order_by_distance(self):
domain = Domain([ContinuousVariable(x) for x in "ab"])
reference = Table.from_numpy(domain, [[1, 0]])
data = Table.from_numpy(domain, [[1, 0.1], [2, 0], [1, 0], [0, 0.1], [0.1, 0]])
self.send_signal(self.widget.Inputs.data, data)
self.send_signal(self.widget.Inputs.reference, reference)

output = self.get_output(self.widget.Outputs.data)
expected = [[1, 0], [1, 0.1], [0.1, 0], [2, 0], [0, 0.1]]
np.testing.assert_array_equal(output.X, expected)
dst = output.get_column("distance").tolist()
self.assertTrue(dst == sorted(dst)) # check distance in ascending order

# test on bigger set
self.send_signal(self.widget.Inputs.data, self.iris)
self.send_signal(self.widget.Inputs.reference, self.iris[:1])
dst = self.get_output(self.widget.Outputs.data).get_column("distance").tolist()
self.assertTrue(dst == sorted(dst)) # check distance in ascending order


if __name__ == "__main__":
unittest.main()