Faiss小记

这篇文章首先介绍一下faiss中的Inverted Index和Product Quantization,然后使用faiss进行一些向量检索的实验。

Inverted Index

中文翻译成倒排索引其实不是很恰当,我们看看维基百科是如何介绍Inverted Index的:

In computer science, an inverted index (also referred to as a postings file or inverted file) is a database index storing a mapping from content, such as words or numbers, to its locations in a table, or in a document or a set of documents (named in contrast to a forward index, which maps from documents to content). The purpose of an inverted index is to allow fast full-text searches, at a cost of increased processing when a document is added to the database. The inverted file may be the database file itself, rather than its index. It is the most popular data structure used in document retrieval systems,[1] used on a large scale for example in search engines. Additionally, several significant general-purpose mainframe-based database management systems have used inverted list architectures, including ADABAS, DATACOM/DB, and Model 204.

Inverted Index的映射关系是documents—> words, 而Forward Index的映射关系是words—> documents,用geeksforgeeks中的一个例子表示:

Inverted Index
image
imageForward Index

油管视频对Inverted Index的解释:
image

在Faiss中,所有的IndexIVF*类型的Index对象都使用了Inverted File System来加速检索,其过程为:

  • 将整个特征空间划分成nlist个cell (cluster)
  • database (gallery)中的每个向量都被分配到其中一个cell,并形成nlist个inverted files
  • 在检索时,只有nprobe个inverted files被挑选出来,query和这些files中的向量进行比较
    如果与words\documents的例子进行对比,这里的word相当于cluster,documents相当于vectors吗?

PQ(Product Quantization)

用下面这张图为例来理解PQ的原理
image
假设我们考虑的向量是128维的,将这128维向量划分成4个部分,每个部分都是一个32维向量

  • 1对各部分向量进行聚类,每个部分聚成256类(8bit即可表示索引)
  • 2将待查询向量库进行量化,这样每个向量都可以用4个索引来表示(4*8=32bits)
  • 3有一个query向量,我们首先计算该向量各部分与对应部分聚类中心的距离,得到一个256*4的距离矩阵(每个距离都是32维向量计算的结果)
  • 4当需要计算query向量与库中某个向量的距离时,只需要进行4次查表即可完成

可以比较一下暴力计算和使用PQ计算的效率。暴力计算需要M次128维的向量距离计算,PQ需要\(256*4\)次32维的向量计算和\(M*4\)次查表。

Faiss介绍

Overview

Faiss是围绕Index对象建立的,Index封装了一组数据库向量,并对它们进行一些预处理,以提高搜索效率。大多数Index都有一个训练过程,通过这个过程分析这些向量的分布。(Faiss处理的矩阵是32-bit浮点数的)

实验

  • IndexFlatL2、IndexFlatIP
    图1
    image
    图2
    image
    图3
    image
  • IndexIVFFlat
    IVF(Inverted File System)
    image
  • IndexIVFPQ
    PQ(Product Quantization)
    image
posted @ 2021-07-29 23:21  渐渐的笔记本  阅读(286)  评论(0编辑  收藏  举报