mirror of
https://github.com/facebookresearch/faiss.git
synced 2026-10-11 22:50:00 +00:00
Add Python HNSW tutorial (#5260)
Summary: This PR adds a Python HNSW tutorial corresponding to the existing C++ HNSW tutorial. The example creates synthetic vectors, builds an IndexHNSWFlat index, runs a search, and prints the nearest-neighbor IDs and distances for the final queries. Pull Request resolved: https://github.com/facebookresearch/faiss/pull/5260 Reviewed By: mnorris11 Differential Revision: D107272616 Pulled By: alibeklfc fbshipit-source-id: 721d7a1a95aa79150d6cb9653bd803065c82dcd7
This commit is contained in:
committed by
meta-codesync[bot]
parent
480f917900
commit
506600962f
@@ -0,0 +1,41 @@
|
||||
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
#
|
||||
# This source code is licensed under the MIT license found in the
|
||||
# LICENSE file in the root directory of this source tree.
|
||||
|
||||
import numpy as np
|
||||
|
||||
import faiss
|
||||
|
||||
|
||||
d = 64 # dimension
|
||||
nb = 100000 # database size
|
||||
nq = 10000 # number of queries
|
||||
|
||||
np.random.seed(1234)
|
||||
|
||||
xb = np.random.random((nb, d)).astype("float32")
|
||||
xb[:, 0] += np.arange(nb) / 1000.0
|
||||
|
||||
xq = np.random.random((nq, d)).astype("float32")
|
||||
xq[:, 0] += np.arange(nq) / 1000.0
|
||||
|
||||
k = 4
|
||||
|
||||
index = faiss.IndexHNSWFlat(d, 32) # M=32: neighbors per node
|
||||
index.hnsw.efConstruction = 40 # graph construction quality
|
||||
index.add(xb)
|
||||
index.hnsw.efSearch = 64 # higher = better recall, slower
|
||||
|
||||
# sanity check
|
||||
D, I = index.search(xb[:5], k)
|
||||
print(I)
|
||||
print(D)
|
||||
|
||||
D, I = index.search(xq, k)
|
||||
|
||||
print("I=")
|
||||
print(I[-5:])
|
||||
|
||||
print("D=")
|
||||
print(D[-5:])
|
||||
Reference in New Issue
Block a user