【大语言模型】应用: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的原理,敬请关注!

相关推荐
樊小肆17 分钟前
agent 不报错才最吓人:自研编码工具半年,我踩了 10 个"看着正常"的运行时坑
前端·人工智能·agent
用户9860239656127 分钟前
Gemini Tool Retrieval:工具越来越多,Agent 如何按需读取参数说明?
人工智能
用户19172912708336 分钟前
Agent 工具面裁剪:动态暴露与渐进披露(附 Python 代码)
人工智能
AI前端工程狮38 分钟前
我给 MCP 长任务加进度条,五步只显示了一步
javascript·人工智能·程序员
TsingtaoAI39 分钟前
VeyForge:构建具身智能的AI 3D资产与Sim-to-Real数据引擎
人工智能·机器学习
螺丝钉tina1 小时前
[Playwright] [21][AI] 千问生成测试的完整 mini demo
人工智能
高洁011 小时前
世界模型的因果内核:从预测表象到理解机制
人工智能·python·深度学习·transformer·迁移学习
Forget the Dream2 小时前
Spring AI 2.0 系列(三):ChatClient 与 ChatModel:Spring AI 2.0 的两层职责
java·人工智能·spring·springai
syso_稻草人2 小时前
qwen-image-2.1 姿态控制拆解:SDPose 提骨架 + Fun-ControlNet-Union 锁姿势,换人换景不换姿势
人工智能·stable diffusion·prompt·提示词优化·qwen-image
Baihai_IDP2 小时前
大模型 API 真的在赔本赚吆喝吗?聊聊 Token 背后的真实成本
人工智能·llm·aigc