10 分鐘打造文本搜索引擎,附詳細(xì)教程
超越傳統(tǒng)基于關(guān)鍵詞的搜索,提高搜索相關(guān)性。
科普:什么是神經(jīng)搜索 (Neural Search)
神經(jīng)搜索 (Neural Search) 是指利用深度神經(jīng)網(wǎng)絡(luò),搜索圖像、視頻、文本等各種非結(jié)構(gòu)化數(shù)據(jù)。與傳統(tǒng)基于文本標(biāo)簽的搜索相比,神經(jīng)搜索更加全面和有針對(duì)性。
教程:快速創(chuàng)建文本搜索引擎
目的:創(chuàng)建一個(gè)文本數(shù)據(jù)的神經(jīng)搜索應(yīng)用。
原理:輸入查詢句子,與數(shù)據(jù)集中的句子進(jìn)行匹配并輸出匹配結(jié)果。
DocArray 參考文檔:
https://docarray.jina.ai/
數(shù)據(jù)集 (Pride & Prejudice e-book) 下載:
https://www.gutenberg.org/files/1342/1342-0.txt
安裝依賴
從 PyPI 安裝 DocArray,方法如下:
1. 通過(guò) Pip 安裝:?pip install docarray?
2. 通過(guò) conda 安裝:?conda install -c conda-forge docarray?
代碼詳解
第一步:從 URL 加載數(shù)據(jù)集,將其轉(zhuǎn)換為文本,并放入?Document?(Jina 中一個(gè)基礎(chǔ)的數(shù)據(jù)類型)。
from docarray import Document, DocumentArray
doc = Document(uri="https://www.gutenberg.org/files/1342/1342-0.txt").load_uri_to_text()
第二步:由于數(shù)據(jù)集 Pride & Prejudice e-book 是一系列長(zhǎng)句子,我們需要先將其進(jìn)行分詞,再放到?DocumentArray?中。
每重起一行,就用?‘\n’?來(lái)分割句子。最終這個(gè)句子將以?Document?的形式,存儲(chǔ)在?DocumentArray?中。
第三步:特征向量化(將特征轉(zhuǎn)換為向量索引)。這里的特征就是?DocumentArray?中每個(gè)?Document?的向量。
特征向量化的實(shí)現(xiàn)方法眾多,這里推薦使用特征哈希 (feature hashing) 方法,因?yàn)樗\(yùn)行更迅速、占用空間更少。
特征哈希的工作原理,是獲取特征并應(yīng)用一個(gè)哈希函數(shù),該函數(shù)可以對(duì)值 (value) 進(jìn)行散列,并將其作為索引返回。
DocArray 極大簡(jiǎn)化了這個(gè)過(guò)程:
# break large text into smaller chunks
docs = DocumentArray(Document(text = s.strip()) for s in doc.text.split('\n') if s.strip())
# apply feature hashing to embed the DocumentArray
docs.apply(lambda doc: doc.embed_feature_hashing())
# query sentence
query = (Document(text="she entered the room").embed_feature_hashing().match(docs, limit=5, exclude_self=True,
metric="jaccard", use_scipy=True))
# print the results
print(query.matches[:, ('text', 'scores__jaccard')])
第四步:獲取輸出。將查詢句子轉(zhuǎn)換為? Document?,并對(duì)其進(jìn)行向量化,然后與?DocumentArray?中?Document?的向量進(jìn)行匹配。
輸入《傲慢與偏見(jiàn)》中句子「she entered the room」,查詢結(jié)果如下:

以上就是創(chuàng)建文本搜索引擎的完整過(guò)程,查看 Colab 請(qǐng)?jiān)L問(wèn)鏈接:
https://colab.research.google.com/github/jina-ai/tutorial-notebooks/blob/main/neural_text_search.ipynb#scrollTo=4glBnUHBiAwp
期待你能用 Jina 全家桶產(chǎn)品,創(chuàng)建更多有意思的 demo~
參考資料:
https://docarray.jina.ai
https://github.com/jina-ai/docarray
https://docs.jina.ai