高階 · 公開核心+會員工作紙 Meta · 向量搜尋

FAISS:向量相似度搜尋(ANN 函式庫,唔係完整資料庫)

Facebook AI Similarity Search · faiss-cpu · RAG 檢索 · 聯絡 psyche@mail.grokbot.com

學習貼士

學習貼士

  • 函式庫≠完整向量 DB。
  • 先 faiss-cpu+FlatL2。
  • RAG=embed→索引→top-k。
  • 非贊助;跟官方。

課節進度

開始學習吧!勾選完成的課節。

0% 完成(0/10 課節)

  • 11. 是什麼
  • 22. 安裝
  • 33. FlatL2 vs IVF
  • 44. 建索引+搜尋
  • 55. 對照
  • 66. RAG/OPC
  • 77. 三個範例
  • 88. 官方來源
  • 99. 練習
  • 1010. 常見問題

提示:滾動到課節會自動標記完成;點擊課節仍可標記/取消(存於本機)。

一句話:喺向量堆入面快搵最近鄰——RAG 檢索核心之一。

1. 是什麼/為什麼(公開)

  • Meta 開源相似度搜尋。
  • 精確/ANN 最近鄰;CPU/GPU。
  • 唔係完整向量 DB。
  • 研究/自建/GPU/Python ML。

2. How-to:安裝(faiss-cpu/conda)

  1. venv 再裝套件。
  2. pip install faiss-cpu numpy。
  3. GPU 後話;先 CPU。
  4. " data-en="Verify:
    python -c "import faiss; print(faiss.__version__)"
    " data-i18n-html="1">import faiss 印版本。
裝 faiss-cpu,import faiss。

3. IndexFlatL2 vs IVF(基礎)

類型特點何時用
IndexFlatL2精確 L2;簡單細中量、教學
IndexIVFFlat 等分區近似搜尋大集合
  • IVF:train → add;調 nprobe。
  • 進階見官方;先 Flat+IVF。

4. 由 embeddings 建索引+k-NN 搜尋

float32、(n, d):

import numpy as np
import faiss

d = 128          # 向量維度(要同 embedding 模型一致)
nb = 1000        # 資料庫向量數
nq = 5           # 查詢數
k = 4            # 每個 query 取幾個鄰居

xb = np.random.random((nb, d)).astype('float32')
xq = np.random.random((nq, d)).astype('float32')

index = faiss.IndexFlatL2(d)
print('is_trained', index.is_trained)  # Flat 通常已 ready
index.add(xb)
print('ntotal', index.ntotal)

D, I = index.search(xq, k)  # D=距離, I=索引位置
print(I[:2])
print(D[:2])
  • I=列號;文字放旁路 metadata。
  • write_index/read_index。

5. FAISS vs Chroma/pgvector/Qdrant

FAISSChromapgvectorQdrant/Weaviate
定位ANN 函式庫原型友好Postgres 擴生產向
過濾/運維自建基本SQL強
何時揀效能自控試作已有 PG服務化

詳見向量庫高階課。

6. RAG/OPC 怎麼用 FAISS

  • chunk→embed→add→search→LLM。
  • OPC 本機 KB;寫入多就升向量庫。
  • 唔 embed 秘密;ACL;審計注入。

7. 三個實作範例

A. 概念 Python:FlatL2

跑第 4 節;調 k。

B. RAG 檢索草圖(偽碼)

# chunks: list[str]  texts: 同序 metadata
# emb = embed_fn(chunks) -> np.ndarray (n, d) float32
index = faiss.IndexFlatL2(d)
index.add(emb)
faiss.write_index(index, "kb.faiss")

q = embed_fn([question])  # (1, d)
D, I = index.search(q, k=5)
ctx = [chunks[i] for i in I[0]]
# prompt = f"根據以下內容回答:\n" + "\n---\n".join(ctx)

embed 接 Ollama/雲端。

C. 批次建索引+IVF 草圖

nlist = 100  # 分區數(視資料量調整)
quantizer = faiss.IndexFlatL2(d)
index = faiss.IndexIVFFlat(quantizer, d, nlist)
assert not index.is_trained
index.train(xb)          # 需要足夠訓練向量
index.add(xb)
index.nprobe = 10        # 搜尋時探訪分區數
D, I = index.search(xq, k)

資料少用 Flat;IVF 要夠 train。

9. 練習清單

  • □ 安裝+import
  • □ FlatL2 跑通
  • □ 持久化
  • □ 迷你 RAG
  • □ 選型一句

常見問題

FAISS 係咪向量資料庫?

係函式庫;完整 DB 另見向量庫課。

該裝 faiss-cpu 定 faiss-gpu?

先 CPU;GPU 要對齊 CUDA。

IndexFlatL2 同 IVF 點揀?

細→Flat;大→IVF。

點樣接 RAG?

embed→索引→top-k→LLM。

🔒 會員專屬:索引選擇・Embedding 管線・OPC RAG 草圖

解鎖高階工作紙。會員 HK$50/月。

登入解鎖 開通會員

課程完成標記

登入會員後可將整門課標記完成並同步至儀表板。