可以试试faiss,,安装pip install faiss-cpu或者faiss-gpu
import numpy as np
import faiss
# 创建一些随机向量
d = 64 # 向量维度
nb = 1000 # 向量数量
np.random.seed(1234) # 设置随机种子
xb = np.random.random((nb, d)).astype('float32')
# 创建索引
index = faiss.IndexFlatL2(d) # 使用 L2 距离
index.add(xb) # 添加向量到索引
# 查询
nq = 5 # 查询的向量数量
xq = np.random.random((nq, d)).astype('float32') # 生成查询向量
D, I = index.search(xq, k=10) # 搜索最近的 10 个邻居
print(I) # 输出最近邻的索引还有annoy,,安装pip install annoyfrom annoy import AnnoyIndex
f = 40 # 向量维度
t = AnnoyIndex(f, 'angular') # 使用角度距离
# 添加向量
for i in range(1000):
v = [random.gauss(0, 1) for z in range(f)]
t.add_item(i, v)
t.build(10) # 建立树
t.save('test.ann') # 保存索引
# 查询
print(t.get_nns_by_item(0, 10)) # 查找与第 0 个向量最近的 10 个向量 网友回复


