查看原文
其他

10 分钟打造文本搜索引擎,附详细教程

Emily Jina AI 2023-03-21

超越传统基于关键词的搜索,提高搜索相关性


科普:什么是神经搜索 (Neural Search)


神经搜索 (Neural Search) 是指利用深度神经网络,搜索图像、视频、文本等各种非结构化数据。与传统基于文本标签的搜索相比,神经搜索更加全面和有针对性。


更多详情请参见:



教程:快速创建文本搜索引擎


目的:创建一个文本数据的神经搜索应用。


原理:输入查询句子,与数据集中的句子进行匹配并输出匹配结果。


DocArray 参考文档:

https://docarray.jina.ai/


数据集 (Pride & Prejudice e-book) 下载:

https://www.gutenberg.org/files/1342/1342-0.txt


安装依赖


从 PyPI 安装 DocArray,方法如下:


1. 通过 Pip 安装: pip install docarray 


2. 通过 conda 安装: conda install -c conda-forge docarray 


代码详解


第一步:从 URL 加载数据集,将其转换为文本,并放入 Document (Jina 中一个基础的数据类型)。


from docarray import Document, DocumentArraydoc = Document(uri="https://www.gutenberg.org/files/1342/1342-0.txt").load_uri_to_text()


第二步:由于数据集 Pride & Prejudice e-book 是一系列长句子,我们需要先将其进行分词,再放到 DocumentArray 中。


每重起一行,就用 ‘\n’ 来分割句子。最终这个句子将以 Document 的形式,存储在 DocumentArray 中。


第三步:特征向量化(将特征转换为向量索引)。这里的特征就是 DocumentArray 中每个 Document 的向量。


特征向量化的实现方法众多,这里推荐使用特征哈希 (feature hashing) 方法,因为它运行更迅速、占用空间更少。


特征哈希的工作原理,是获取特征并应用一个哈希函数,该函数可以对值 (value) 进行散列,并将其作为索引返回。


DocArray 极大简化了这个过程:


# break large text into smaller chunksdocs = DocumentArray(Document(text = s.strip()) for s in doc.text.split('\n') if s.strip())
# apply feature hashing to embed the DocumentArraydocs.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 resultsprint(query.matches[:, ('text', 'scores__jaccard')])


第四步:获取输出。将查询句子转换为  Document ,并对其进行向量化,然后与 DocumentArray Document 的向量进行匹配。


输入《傲慢与偏见》中句子「she entered the room」,查询结果如下:



以上就是创建文本搜索引擎的完整过程,查看 Colab 请点击文末阅读全文,或访问链接:


https://colab.research.google.com/github/jina-ai/tutorial-notebooks/blob/main/neural_text_search.ipynb#scrollTo=4glBnUHBiAwp


期待你能用 Jina 全家桶产品,创建更多有意思的 demo~


参考资料:

https://docarray.jina.ai

https://github.com/jina-ai/docarray

https://docs.jina.ai




神经搜索、深度学习、推荐系统


教程、Demo、干货分享


扫码备注加入讨论组

更多精彩内容(点击图片阅读)


您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存