本文介绍各种用于向量检索的向量相似性计算方法,将会简单介绍各种方法的优缺点等信息,并用toy example给出代码示例。
1. 余弦相似度
使用sklearn.metrics.pairwise.cosine_similarity实现。
最终得到的值会在[-1,1]之间。
API官方文档:sklearn.metrics.pairwise.cosine_similarity — scikit-learn 1.1.2 documentation
对计算公式的介绍:https://scikit-learn.org/stable/modules/metrics.html#cosine-similarity
计算公式:
k
(
x
,
y
)
=
x
y
⊤
∥
x
∥
∥
y
∥
k(x, y) = \frac{x y^\top}{\|x\| \|y\|}
k(x,y)=∥x∥∥y∥xy⊤
计算一组向量之间的两两相似度,代码撰写方法:
from sklearn.metrics.pairwise import cosine_similarity
cos_sim_matrix = cosine_similarity(train_feature)
#入参是一个二维矩阵,每行是一个样本特征
2. 线性核(点积)
2.1 sklearn实现
使用sklearn.metrics.pairwise.linear_kernel实现。
API官方文档:sklearn.metrics.pairwise.linear_kernel — scikit-learn 1.1.2 documentation
计算公式:
k
(
x
,
y
)
=
x
⊤
y
k(x, y) = x^\top y
k(x,y)=x⊤y
3. 向量检索
解决方案
- Faiss包:L2和/或点积向量。速度飞快
原理:聚合键,基于簇中心查找邻居
facebookresearch/faiss: A library for efficient similarity search and clustering of dense vectors. - annoy库:可以在大规模数据上检索(200W条已试可用)
spotify/annoy: Approximate Nearest Neighbors in C++/Python optimized for memory usage and loading/saving to disk
pip install annoy
示例代码:
#用TFIDF做向量(一个做文本表征的示例),然后用annoy算法计算相似度
#TFIDF部分
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf=TfidfVectorizer(max_features=500)
sp_tfidf=tfidf.fit_transform(corpus) #corpus是一个文本列表
#annoy部分
from annoy import AnnoyIndex
from tqdm import tqdm
#存储
f=sp_tfidf.shape[1] # Length of item vector that will be indexed
t = AnnoyIndex(f, 'angular')
for i in tqdm(range(len(corpus))):
t.add_item(i, sp_tfidf[i].toarray().squeeze()) #第2个元素是一个数组
t.build(10) # 10 trees
t.save('存储路径.ann')
#调用
u = AnnoyIndex(f, 'angular')
u.load('存储路径.ann') # super fast, will just mmap the file
print(u.get_nns_by_item(0, 1000)) # will find the 1000 nearest neighbors
#返回值是向量的索引
#如果用get_nns_by_vector的话第一个入参就改成向量,如sp_tfidf[0].toarray().squeeze()
理论和术语
- 单调性
4. 排序
一般来说顺序是先检索(返回一个集合)然后再排序
- 拟合回归模型并计算MSE
参考资料:Recommending movies: ranking | TensorFlow Recommenders - Listwise ranking
参考资料:Listwise ranking | TensorFlow Recommenders
5. 向量存储(向量数据库)
- VBASE
其他参考资料
- 我还没看:
- 最近邻搜索(NN)、最大内积搜索(MIPS)与(A)LSH算法 - 知乎
- ChatGPT盛行的当下,向量数据库为大模型配备了一个超级大脑
- (2021 NeurIPS) SPANN: Highly-efficient Billion-scale Approximate Nearest Neighbor Search
- (2020 SIGIR) ColBERT: Efficient and Effective Passage Search via Contextualized Late Interaction over BERT
- facebookresearch/contriever: Contriever: Unsupervised Dense Information Retrieval with Contrastive Learning
- (2023 TMLR) Unsupervised Dense Information Retrieval with Contrastive Learning