Skip to content
Open
Show file tree
Hide file tree
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
5 changes: 4 additions & 1 deletion faiss/utils/simd_impl/distances_autovec-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,10 @@ float VectorDistance<METRIC_Canberra, SL>::operator()(
float accu = 0;
for (size_t i = 0; i < this->d; i++) {
float xi = x[i], yi = y[i];
accu += fabs(xi - yi) / (fabs(xi) + fabs(yi));
float denominator = fabs(xi) + fabs(yi);
if (denominator != 0.0f) {
accu += fabs(xi - yi) / denominator;
}
}
return accu;
}
Expand Down
26 changes: 26 additions & 0 deletions tests/test_extra_distances.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,32 @@ def test_canberra(self):
scipy.spatial.distance.canberra, faiss.METRIC_Canberra
)

def test_canberra_zero_denominator(self):
xq = np.array([[0.0, 0.0]], dtype="float32")
yb = np.array(
[
[0.0, 0.0],
[1.0, 0.0],
[0.0, 2.0],
],
dtype="float32",
)
expected = np.array([[0.0, 1.0, 1.0]], dtype="float32")

distances = faiss.pairwise_distances(
xq, yb, faiss.METRIC_Canberra
)
self.assertTrue(np.all(np.isfinite(distances)))
self.assertTrue(np.allclose(distances, expected))

index = faiss.IndexFlat(2, faiss.METRIC_Canberra)
index.add(yb)
distances, labels = index.search(xq, 3)
self.assertTrue(np.all(np.isfinite(distances)))
self.assertNotIn(-1, labels[0])
self.assertEqual(set(labels[0].tolist()), {0, 1, 2})
self.assertTrue(np.allclose(np.sort(distances[0]), expected[0]))

def test_braycurtis(self):
self.run_simple_dis_test(
scipy.spatial.distance.braycurtis, faiss.METRIC_BrayCurtis
Expand Down