https://github.com/justinshenk/closely
Python library for finding the closest pairs in an array
https://github.com/justinshenk/closely
closest-pair-of-points neighbors points similarity
Last synced: over 1 year ago
JSON representation
Python library for finding the closest pairs in an array
- Host: GitHub
- URL: https://github.com/justinshenk/closely
- Owner: JustinShenk
- License: mit
- Created: 2019-05-22T07:56:03.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2019-06-17T15:34:44.000Z (about 7 years ago)
- Last Synced: 2025-02-05T16:04:59.401Z (over 1 year ago)
- Topics: closest-pair-of-points, neighbors, points, similarity
- Language: Python
- Homepage:
- Size: 260 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# :triangular_ruler: Closely
[](https://badge.fury.io/py/closely) [](https://travis-ci.com/justinshenk/closely) [](https://zenodo.org/badge/latestdoi/187990744)
Find the closest pairs in an array.
Closely compares distances of arrays/embeddings and sorts them.
### Getting Started
```bash
pip install closely
```
or install from source:
```bash
git clone https://github.com/justinshenk/closely
cd closely
pip install .
```
### How to use
```python
import closely
# X is an n x m numpy array
pairs, distances = closely.solve(X, n=1)
```
You can specify how many pairs you want to identify with `n`.
#### Distance Metric
The distance metric can be changed from the default `euclidean` to any supported by [`scipy.spatial.distance.cdist`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html), eg, `cosine`, `hamming`, etc:
```python
closely.solve(X, metric='cosine`)
```
### Example
```python
import closely
import numpy as np
import matplotlib.pyplot as plt
# Create dataset
X = np.random.random((100,2))
pairs, distances = closely.solve(X, n=1)
# Plot points
z, y = np.split(X, 2, axis=1)
fig, ax = plt.subplots()
ax.scatter(z, y)
for i, txt in enumerate(X):
if i in pairs:
ax.annotate(i, (z[i], y[i]), color='red')
else:
ax.annotate(i, (z[i], y[i]))
plt.show()
```
Check `pairs`:
```ipython
In [10]: pairs
Out[10]:
array([[ 7, 16],
[96, 50]])
```
Output:

### Credit and Explanation
Python code for ordering distance matrices modified from [Andriy Lazorenko](https://medium.com/@andriylazorenko/closest-pair-of-points-in-python-79e2409fc0b2), packaged and made useful for >2 features by Justin Shenk.