AI一点通:向量数据库FAISS 平均延迟的测量

FAISS(Facebook AI Similarity Search)是一款强大的库,用于高效地进行相似性搜索和密集向量的聚类。它针对高性能和可扩展性进行了优化,是处理大规模数据集和计算最近邻选择的绝佳选择。

在这篇简短的博客中,我们将探讨如何在搭载Apple M1处理器的 Mac 上使用 FAISS 来测量搜索 1000 条记录的平均延迟。

设置环境

首先,您需要安装 FAISS 并确保您拥有合适的开发工具和库。您可以使用 pip 来安装 FAISS:

shell 复制代码
pip install faiss-cpu

接下来,我们通过导入必要的包和定义常量来设置我们的环境。

python 复制代码
import faiss
import numpy as np
import time

# Define constants
num_vectors = 500000
dim = 20
num_searches = 1000
k = 100 # Number of nearest neighbors to retrieve

生成随机向量

FAISS 处理密集向量。这里,我们生成模拟数据集的随机向量:

python 复制代码
# Create random vectors
np.random.seed(42) # For reproducibility
vectors = np.random.random((num_vectors, dim)).astype('float32')

初始化 FAISS 索引

我们使用 IndexFlatL2 初始化 FAISS 索引,它计算向量之间的欧几里得(L2)距离:

python 复制代码
# Initialize FAISS index
index = faiss.IndexFlatL2(dim) # L2 distance (Euclidean)

# Add vectors to the index
index.add(vectors)

测量延迟

为了测量搜索操作的延迟,我们生成一个查询向量并进行多次搜索,记录每次搜索所用的时间:

python 复制代码
# Generate query vector
query_vector = np.random.random((1, dim)).astype('float32')

# Measure latency of searches
latencies = []
for _ in range(num_searches):
  start_time = time.time()
  D, I = index.search(query_vector, k) # search for k nearest neighbors
  latencies.append(time.time() - start_time)

计算平均延迟

最后,我们计算以毫秒为单位的平均延迟并打印结果:

python 复制代码
# Calculate average latency in milliseconds
average_latency = np.mean(latencies) * 1000 # Convert to milliseconds
print(f'Average latency for {num_searches} searches: {average_latency:.4f} ms')

结果

在搭载 Apple M1 处理器的 Mac 上运行上述代码,我们在 1000 次搜索中的平均延迟大约为 7 毫秒。这一性能展示了 FAISS 的高效性以及 Apple M1 处理器在机器学习任务中的强大能力。

阅读英文

faiss-vector-store-latency-check

AI好书推荐

AI日新月异,再不学来不及了。但是万丈高楼拔地起,离不开良好的基础。您是否有兴趣了解人工智能的原理和实践? 不要再观望! 我们关于 AI 原则和实践的书是任何想要深入了解 AI 世界的人的完美资源。 由该领域的领先专家撰写,这本综合指南涵盖了从机器学习的基础知识到构建智能系统的高级技术的所有内容。 无论您是初学者还是经验丰富的 AI 从业者,本书都能满足您的需求。 那为什么还要等呢?

人工智能原理与实践 全面涵盖人工智能和数据科学各个重要体系经典

北大出版社,人工智能原理与实践 人工智能和数据科学从入门到精通 详解机器学习深度学习算法原理

相关推荐
veminhe2 天前
关于下载pip install faiss-cpu失败的问题
python·pip·faiss
程序员佳佳2 天前
我在 Windows 和低配 Linux 上做 RAG:Milvus、FAISS、向量 API 中转的中立实测
linux·人工智能·windows·gpt·aigc·milvus·faiss
li星野4 天前
FAISS 详解:原理、使用与面试指南——向量检索的基石
面试·职场和发展·faiss
尽兴-5 天前
2.3 向量数据库:FAISS、Chroma、Milvus、Pinecone、Qdrant
pinecone·milvus·faiss·向量数据库·chroma·qdrant
codefan※9 天前
RAG 加速指南:Faiss / Milvus / Qdrant 向量库选型与调优
知识图谱·milvus·faiss·向量数据库·rag·qdrant
Esaka_Forever12 天前
FAISS (Facebook AI Similarity Search)
人工智能·faiss
Muyuan199823 天前
31.Cursor 初体验:用 AI Agent 给 PaperPilot 做一次最小工程重构
人工智能·python·重构·django·fastapi·faiss
Muyuan199824 天前
29.从 FAISS 到 Milvus:给我的 RAG Agent 项目加一层可替换的向量检索后端
fastapi·milvus·faiss
qq_283720051 个月前
LangChain+FAISS 向量数据库搭建轻量化 RAG 应用
数据库·langchain·faiss
qq_283720051 个月前
纯本地 RAG 系统部署详细教程:DeepSeek+BGE+FAISS
faiss