使用深度学习嵌入和 FAISS 进行实时内存语义搜索

本文介绍了如何使用BERT对短文本进行编码,通过FAISS建立索引以实现CPU平台上的语义搜索。示例中展示了在Python中使用SentenceTransformer和FAISS库处理20Newsgroups数据集,进行机器学习和深度学习的实践应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

我们使用基于BERT的句子转换器对短文本进行编码,然后使用内存搜索引擎 FAISS 对结果进行索引;最终很容易的在 CPU 平台上实现语义搜索的实时查找。

安装包

!pip install faiss-cpu
!pip install -U sentence-transformers

import libraries

import numpy as np
import torch
import os
import pandas as pd
import faiss
import time
from sklearn.datasets import fetch_20newsgroups
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('distilbert-base-nli-mean-tokens')
model.encode(['how are you'])[0].shape
(768,)

获取演示数据

data = fetch_20newsgroups()['data']
subjects = [item.split('\n')[1] for item in data]
subjects[:10]
['Subject: WHAT car is this!?',
 'Subject: SI Clock Poll - Final Call',
 'Subject: PB questions...',
 'Subject: Re: Weitek P9000 ?',
 'Subject: Re: Shuttle Launch Question',
 'Subject: Re: Rewording the Second Amendment (ideas)',
 'Subject: Brain Tumor Treatment (thanks)',
 'Subject: Re: IDE vs SCSI',
 'Subject: WIn 3.0 ICON HELP PLEASE!',
 'Subject: Re: Sigma Designs Double up??']
encoded_data = model.encode(subjects)
encoded_data.shape
(11314, 768)

建立数据索引

index = faiss.IndexIDMap(faiss.IndexFlatIP(768))
index.add_with_ids(encoded_data, np.array(range(0, len(encoded_data))))

演示,将索引序列化到磁盘,序列化后的索引可以导出到任何一台机器上来托管搜索引擎

faiss.write_index(index, '20news')

出于演示目的从磁盘读回索引,所谓的反序列化

index = faiss.read_index('20news')

语义搜索

def search(query):
    start=time.time()
    query_vector = model.encode([query])
    k = 5
    top_k = index.search(query_vector, k)
    print('spent time: {}'.format(time.time()-start))
    return [subjects[_id] for _id in top_k[1].tolist()[0]]
# type the query
# query=str(input())

query = "auto"
results=search(query)
print('results :')
for result in results:
   print('\t',result)
spent time: 0.035505056381225586
results :
	 Subject: (w)rec.autos
	 Subject: Re: DRIVE
	 Subject: WHAT car is this!?
	 Subject: Re: WHAT car is this!?
	 Subject: Car AMP [Forsale]

代码链接

文末github link

最后的话

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值