Search code examples
c++face-recognitioncosine-similarityfaiss

What is the equivalent of python's faiss.normalize_L2() in C++?


I want to perfom similarity search using FAISS for 100k facial embeddings in C++. For the distance calculator I would like to use cosine similarity. For this purpose, I choose faiss::IndexFlatIP .But according to the documentation we need to normalize the vector prior to adding it to the index. The documentation suggested the following code in python:

index = faiss.IndexFlatIP(dimensions)
faiss.normalize_L2(embeddings)

But as I would like to implement the same thing in C++, I noticed I couldnot find any functions in C++ that is similar to the one in python faiss.normalize_L2(). Can anyone help? Thank's in advance.


Solution

  • You can build and use the C++ interface of Faiss library (see this).

    If you just want L2 normalization of a vector in C++:

    std::vector<float> data;
    
    float sum = 0;
    for (auto item : data) sum += item * item;
    
    float norm = std::sqrt(sum);
    for (auto &item : data) item /= norm;