@@ -335,10 +335,10 @@ def knn(xq, xb, k, metric=METRIC_L2):
335
335
Parameters
336
336
----------
337
337
xq : array_like
338
- Query vectors, shape (nq, d) where d is appropriate for the index.
338
+ Query vectors, shape (nq, d) where the dimension d is that same as xb
339
339
`dtype` must be float32.
340
340
xb : array_like
341
- Database vectors, shape (nb, d) where d is appropriate for the index.
341
+ Database vectors, shape (nb, d) where dimension d is the same as xq
342
342
`dtype` must be float32.
343
343
k : int
344
344
Number of nearest neighbors.
@@ -375,6 +375,56 @@ def knn(xq, xb, k, metric=METRIC_L2):
375
375
raise NotImplementedError ("only L2 and INNER_PRODUCT are supported" )
376
376
return D , I
377
377
378
+ def knn_hamming (xq , xb , k , variant = "hc" ):
379
+ """
380
+ Compute the k nearest neighbors of a set of vectors without constructing an index.
381
+
382
+ Parameters
383
+ ----------
384
+ xq : array_like
385
+ Query vectors, shape (nq, d) where d is the number of bits / 8
386
+ `dtype` must be uint8.
387
+ xb : array_like
388
+ Database vectors, shape (nb, d) where d is the number of bits / 8
389
+ `dtype` must be uint8.
390
+ k : int
391
+ Number of nearest neighbors.
392
+ variant : string
393
+ Function variant to use, either "mc" (counter) or "hc" (heap)
394
+
395
+ Returns
396
+ -------
397
+ D : array_like
398
+ Distances of the nearest neighbors, shape (nq, k)
399
+ I : array_like
400
+ Labels of the nearest neighbors, shape (nq, k)
401
+ """
402
+ # other variant is "mc"
403
+ nq , d = xq .shape
404
+ nb , d2 = xb .shape
405
+ assert d == d2
406
+ D = np .empty ((nq , k ), dtype = 'int32' )
407
+ I = np .empty ((nq , k ), dtype = 'int64' )
408
+
409
+ if variant == "hc" :
410
+ heap = faiss .int_maxheap_array_t ()
411
+ heap .k = k
412
+ heap .nh = nq
413
+ heap .ids = faiss .swig_ptr (I )
414
+ heap .val = faiss .swig_ptr (D )
415
+ faiss .hammings_knn_hc (
416
+ heap , faiss .swig_ptr (xq ), faiss .swig_ptr (xb ), nb ,
417
+ d , 1
418
+ )
419
+ elif variant == "mc" :
420
+ faiss .hammings_knn_mc (
421
+ faiss .swig_ptr (xq ), faiss .swig_ptr (xb ), nq , nb , k , d ,
422
+ faiss .swig_ptr (D ), faiss .swig_ptr (I )
423
+ )
424
+ else :
425
+ raise NotImplementedError
426
+ return D , I
427
+
378
428
379
429
###########################################
380
430
# Kmeans object
0 commit comments