首页/AI/RAG 与向量库速查/FAISS IVF 索引与训练

FAISS IVF 索引与训练

IndexIVFFlat 需要先训练后添加:训练用代表性样本学习聚类中心,nprobe 控制查询扫描的聚类数;数据分布变化较大时应重新训练。

RAG 与向量库速查AI更新于 2026-10-12

训练与查询

训练与查询
import faiss, numpy as np

d = 384; nlist = 1024
quantizer = faiss.IndexFlatL2(d)
index = faiss.IndexIVFFlat(quantizer, d, nlist, faiss.METRIC_L2)
index.train(np.random.rand(200000, d).astype("float32"))
index.add(np.random.rand(1000000, d).astype("float32"))
index.nprobe = 32
D, I = index.search(np.random.rand(1, d).astype("float32"), 10)
训练样本量与 nlist 同阶或更多时聚类更稳定;过少会让部分聚类形同虚设。

易错点

  • add 前跳过 train 直接报错;先 add 后 train 更是无效操作
  • nlist 设置远大于数据规模,大量空聚类浪费训练与查询预算

数据来源与参考

  • FAISS wiki(IVF training / nprobe)
​‌‌​​‌​​​‌‌​‌‌‌‌​‌‌​​​‌‌​‌‌‌​​‌‌​​‌​‌‌‌​​‌‌‌​​​‌​‌‌​‌​​‌​‌‌‌​​​‌​‌‌​‌​​‌​‌‌​​​‌‌​‌‌‌​‌​​​‌‌​‌‌‌‌​​‌​‌‌‌​​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌​‌