人工智能原理与实践 全面涵盖人工智能和数据科学各个重要体系经典
北大出版社,人工智能原理与实践 人工智能和数据科学从入门到精通 详解机器学习深度学习算法原理
我们使用基于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]
代码链接
最后的话
AI日新月异,但是万丈高楼拔地起,离不开良好的基础。您是否有兴趣了解人工智能的原理和实践? 不要再观望! 我们关于 AI 原则和实践的书是任何想要深入了解 AI 世界的人的完美资源。 由该领域的领先专家撰写,这本综合指南涵盖了从机器学习的基础知识到构建智能系统的高级技术的所有内容。 无论您是初学者还是经验丰富的 AI 从业者,本书都能满足您的需求。 那为什么还要等? 立即下单,开始以一种易于访问、引人入胜且实用的方式学习 AI。