【大语言模型】应用:10分钟实现搜索引擎

本文利用20Newsgroup这个数据集作为Corpus(语料库),用户可以通过搜索关键字来进行查询关联度最高的News,实现对文本的搜索引擎:

1. 导入数据集

python 复制代码
from sklearn.datasets import fetch_20newsgroups

newsgroups = fetch_20newsgroups()

print(f'Number of documents: {len(newsgroups.data)}')
print(f'Sample document:\n{newsgroups.data[0]}')

2. 向量化单词

python 复制代码
from sklearn.feature_extraction.text import CountVectorizer
count = CountVectorizer()
count.fit(newsgroups.data)
show_vocabulary(count)

print(f'Size of vocabulary: {len(count.get_feature_names_out())}')

def show_vocabulary(vectorizer):
    words = vectorizer.get_feature_names_out()

    print(f'Vocabulary size: {len(words)} words')

    # we can print ~10 words per line
    for l in np.array_split(words, math.ceil(len(words) / 10)):
        print(''.join([f'{x:<15}' for x in l]))

3. 搜索引擎

python 复制代码
#将语料库进行转化
corpus_bow = count.transform(newsgroups.data)

#提供用户输入,对输入内容进行转化为BoW - Bag of word
query = input("Type your query: ")
query_bow = count.transform([query])

from sklearn.metrics.pairwise import cosine_similarity

#比较输入内容与语料库中的相似度
similarity_matrix = cosine_similarity(corpus_bow, query_bow)
print(f'Similarity Matrix Shape: {similarity_matrix.shape}')

得到Similarity_matrix一共有N行,表示语料库中的文档数。还有一列,代表相似度系数。

第K行的相似度系数,代表用户输入的文本与语料库中第K个文档的相似程度。

我们对相似度矩阵进行排序:

python 复制代码
similarities = pd.Series(similarity_matrix[:, 0])
similarities.head(10)

那么和用户输入最相关的文档就是第一个了!

python 复制代码
print('Best document:')
print(newsgroups.data[top_10.index[0]])

结论:本文利用Cosine_similarity比较文档的相似度,从语料库找出最佳匹配的文档。

如果对单词的向量化,BoW概念有问题可以看下我的另一篇文章。

CSDN

下面一篇文章我会具体分析Cosine_similarity的原理,敬请关注!

相关推荐
蝎子莱莱爱打怪43 分钟前
AI Agent 相关知识扫盲:16 个概念+11张图+38个开源项目推荐
人工智能·github·agent
甲维斯1 小时前
Fable+Codex 《坦克大战3D》双端发布了!
人工智能·ai编程·游戏开发
掘金一周2 小时前
企业中要做智能体,最佳的方案是什么? | 沸点周刊 6.18
前端·人工智能·ai编程
雪隐3 小时前
个人电脑玩AI-04让5060 Ti给你打工——本地claude code编程助理
人工智能·后端
洛宇3 小时前
再谈 AI 时代,程序员的失眠问题。
人工智能
百度Geek说3 小时前
harness-pilot 给代码库加一套"规则说明书"和"自动检查器"
人工智能
程序员cxuan3 小时前
分享一下我最近常用的 10 个 Codex 小技巧。
人工智能·后端·程序员
用户337922545683 小时前
基于 OKF + RAG 构建 Text2SQL 语义层:让 LLM 真正理解你的数据库
人工智能
把所有砖敲烂3 小时前
MiniMax M3 深度实测:单卡部署、代码生成与性能全解析
人工智能