std::vector
to/from np.array
When you would like to directly handle std::vector in the c++ class, you can convert std::vector to np.array by faiss.vector_to_array
. Similarily, you can call faiss.copy_array_to_vector
to convert np.array to std::vector. See python/faiss.py for more details.
import faiss
import numpy as np
D = 2
N = 3
X = np.random.random((N, D)).astype(np.float32)
print(X)
# [[0.8482132 0.17902061]
# [0.07226888 0.15747449]
# [0.41783017 0.9381101 ]]
# Setup
index = faiss.IndexFlatL2(D)
index.add(X)
# Let's see std::vector inside the c++ class (IndexFlatL2)
# We cannot directly read/update them by nparray.
print(type(index.xb)) # <class 'faiss.swigfaiss.FloatVector'>
print(index.xb) # <faiss.swigfaiss.FloatVector; proxy of <Swig Object of type 'std::vector< float > *' at 0x7fd62822a690> >
# Convert std::vector to np.array
xb_np = faiss.vector_to_array(index.xb) # std::vector -> np.array
print(type(xb_np)) # <class 'numpy.ndarray'>
print(xb_np) # [0.8482132 0.17902061 0.07226888 0.15747449 0.41783017 0.9381101 ]
# We can also convert np.array to std::vector
X2 = np.random.random((N, D)).astype(np.float32) # new np.array
X2_std_vector = faiss.FloatVector() # Buffer.
print(type(X2_std_vector)) # <class 'faiss.swigfaiss.FloatVector'>
faiss.copy_array_to_vector(X2.reshape(-1), X2_std_vector) # np.array -> std::vector. Don't forget to flatten the np.array
# The obtained std:vector can be used inside the c++ class
index.xb = X2_std_vector # You can set this in IndexFlatL2 (Be careful. This is dangerous)
print(index.search(x=X2, k=3)) # Works correctly
# (array([[0. , 0.09678471, 0.5692644 ],
# [0. , 0.09678471, 0.23682791],
# [0. , 0.23682791, 0.5692644 ]], dtype=float32), array([[0, 1, 2],
# [1, 0, 2],
# [2, 1, 0]]))
网友评论