自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

解鎖搜索的力量:關(guān)鍵詞、相似性和語義解釋

譯文
開發(fā) 前端 人工智能
本文概述了關(guān)鍵字搜索、相似性搜索和語義搜索技術(shù),深入探討了每種技術(shù)的工作原理,并提供了如何有效使用它們的指導(dǎo)。

譯者 | 李睿

審校 | 重樓

深入研究不同的搜索技術(shù)

為了設(shè)定場景,假設(shè)有一系列關(guān)于各種技術(shù)主題的文本,并希望查找與“機(jī)器學(xué)習(xí)” Machine Learning相關(guān)的信息。接下來將研究關(guān)鍵字搜索、相似性搜索和語義搜索如何提供不同程度的深度和理解,從簡單的關(guān)鍵字匹配到識別相關(guān)概念和場景。

首先看看程序使用的標(biāo)準(zhǔn)代碼組件。

1.使用的標(biāo)準(zhǔn)代碼組件

A.導(dǎo)入的庫

Python 
 import os
 import re
 from whoosh.index import create_in
 from whoosh.fields import Schema, TEXT
 from whoosh.qparser import QueryParser
 from sklearn.feature_extraction.text import TfidfVectorizer
 from sklearn.metrics.pairwise import cosine_similarity
 from transformers import pipeline
 import numpy as np

在這個塊中導(dǎo)入了以下必要的庫:

  • os用于文件系統(tǒng)的操作。
  • re表示正則表達(dá)式。
  • whoosh用于創(chuàng)建和管理搜索索引。
  • scikit-learn用于TF-IDF矢量化和相似度計算。
  • transformers使用深度學(xué)習(xí)模型進(jìn)行特征提取。
  • numpy用于數(shù)值運(yùn)算,特別是排序。

B.文檔初始化樣例

Python 
 # Sample documents used for demonstrating all three search techniques
 documents = [
 "Machine learning is a field of artificial intelligence that uses statistical techniques.",
 "Natural language processing (NLP) is a part of artificial intelligence that deals with the interaction between computers and humans using natural language. ",
 "Deep learning models are a subset of machine learning algorithms that use neural networks with many layers.",
 "AI is transforming the world by automating tasks, providing insights through data analysis, and enabling new technologies like autonomous vehicles and advanced robotics. ",
 "Natural language processing can be challenging due to the complexity and variability of human language. ",
 "The application of machine learning in healthcare is revolutionizing the way diseases are diagnosed and treated.",
 "Autonomous vehicles rely heavily on AI and machine learning to navigate and make decisions.",
 "Speech recognition technology has advanced considerably thanks to deep learning models. "
 ]

定義一個示例文檔列表,其中包含與人工智能、機(jī)器學(xué)習(xí)和自然語言處理中的各種主題相關(guān)的文本。

C.高亮功能

Python 

 def highlight_term(text, term):
 return re.sub(f"({term})", r'\033[1;31m\1\033[0m', text, flags=re.IGNORECASE)

用于美化輸出,以突出顯示文本中的搜索詞。

2.關(guān)鍵字搜索

將搜索查詢與文檔中找到的精確或部分關(guān)鍵字相匹配的傳統(tǒng)方法。

嚴(yán)重依賴于精確的詞匹配和簡單的查詢操作符(AND、OR、NOT)。

A.關(guān)鍵字搜索如何工作

由于搜索查詢是“機(jī)器學(xué)習(xí)”(Machine Learning),因此關(guān)鍵字搜索會查找精確的文本匹配,并且只返回包含“機(jī)器學(xué)習(xí)”(Machine Learning)的文本。一些將被返回的文本示例是“機(jī)器學(xué)習(xí)正在改變許多行業(yè)?!薄白罱_設(shè)了一門機(jī)器學(xué)習(xí)的課程?!?/span>

B.檢查關(guān)鍵字搜索背后的代碼

Python 
 # Function for Keyword Search using Whoosh
 def keyword_search(query_str):
 schema = Schema(content=TEXT(stored=True))
 if not os.path.exists("index"):
 os.mkdir("index")
 index = create_in("index", schema)
 writer = index.writer()
 for doc in documents:
 writer.add_document(content=doc)
 writer.commit()

 with index.searcher() as searcher:
 query = QueryParser("content", index.schema).parse(query_str)
 results = searcher.search(query)
 highlighted_results = [(highlight_term(result['content'], query_str), result.score) for result in results]
 return highlighted_results

使用了Whoosh庫來執(zhí)行關(guān)鍵字搜索。

Schema和TEXT采用單個字段內(nèi)容定義模式。

  • os.path.exists和os.path.existsmkdir:檢查索引目錄是否存在,如果不存在則創(chuàng)建它。
  • create_in:在名為index的目錄中建立索引。
  • writer:打開一個寫入器,將文檔添加到索引中。
  • add_document:向索引中添加文檔。
  • commit:將更改提交到索引。
  • with index.searcher():打開一個搜索器來搜索索引。
  • QueryParser:解析查詢字符串。
  • searcher.search:使用解析后的查詢搜索索引。
  • highlighted_results:高亮顯示結(jié)果中的搜索詞,并存儲結(jié)果及其分?jǐn)?shù)。

將在本文后面檢查關(guān)鍵字搜索輸出和其他搜索技術(shù)。

3.相似性搜索

該方法根據(jù)相關(guān)單詞或主題的存在等特征,將提供的文本與其他文本進(jìn)行比較,從而找到與搜索查詢相似的文本。

A.相似性搜索的工作原理

回到之前相同的搜索查詢“機(jī)器學(xué)習(xí)”,相似度搜索將返回概念上類似的文本,例如“醫(yī)療保健中的人工智能應(yīng)用使用機(jī)器學(xué)習(xí)技術(shù)”和“預(yù)測建模通常依賴于機(jī)器學(xué)習(xí)”。

B.檢查相似度搜索背后的代碼

Python 
 # Function for Similarity Search using Scikit-learn
 def similarity_search(query_str):
 vectorizer = TfidfVectorizer()
 tfidf_matrix = vectorizer.fit_transform(documents)
 query_vec = vectorizer.transform([query_str])
 similarity = cosine_similarity(query_vec, tfidf_matrix)
 similar_docs = similarity[0].argsort()[-3:][::-1] # Top 3 similar documents
 similarities = similarity[0][similar_docs]
 highlighted_results = [(highlight_term(documents[i], query_str), similarities[idx]) for idx, i in enumerate(similar_docs)]
 return highlighted_results

使用Scikit-learn庫編寫了一個函數(shù)來執(zhí)行相似性搜索。

  • TfidfVectorizer:將文檔轉(zhuǎn)換為TF-IDF功能。
  • fit_transform:它將矢量器適配到文檔中,并將文檔轉(zhuǎn)換為TF-IDF矩陣。Fit從文檔列表中學(xué)習(xí)詞匯表,并識別唯一的單詞,以計算它們的TF和IDF值。
  • transform:使用在fit步驟中學(xué)習(xí)的相同詞匯表和統(tǒng)計信息,將查詢字符串轉(zhuǎn)換為TF-IDF向量。
  • cosine_similarity:計算查詢向量和TF-IDF矩陣之間的余弦相似度。
  • argsort()[-3:][::-1]:按相似度降序獲取前3個相似文檔的索引。這一步只與本文相關(guān),如果不想將搜索結(jié)果限制在前3名,可以取消這一步驟。
  • highlighted_results:高亮顯示結(jié)果中的搜索詞,并存儲結(jié)果及其相似性得分。

4.語義搜索

現(xiàn)在進(jìn)入了強(qiáng)大搜索技術(shù)的領(lǐng)域。此方法理解搜索詞的含義/場景,并使用該概念返回文本,即使沒有直接提到搜索詞。

A.語義搜索如何工作

同樣的搜索查詢“機(jī)器學(xué)習(xí)”(Machine Learning),當(dāng)與語義搜索一起應(yīng)用時,會產(chǎn)生與機(jī)器學(xué)習(xí)概念相關(guān)的文本,例如“人工智能和數(shù)據(jù)驅(qū)動的決策正在改變行業(yè)”和“神經(jīng)網(wǎng)絡(luò)是許多人工智能系統(tǒng)的?!?/span>

B.檢查語義搜索背后的代碼

Python 
 # Function for Semantic Search using Transformers

def semantic_search(query_str):
 semantic_searcher = pipeline("feature-extraction", model="distilbert-base-uncased")
 query_embedding = semantic_searcher(query_str)[0][0]
 
 def get_similarity(query_embedding, doc_embedding):
 return cosine_similarity([query_embedding], [doc_embedding])[0][0]
 
 doc_embeddings = [semantic_searcher(doc)[0][0] for doc in documents]
 similarities = [get_similarity(query_embedding, embedding) for embedding in doc_embeddings]
 sorted_indices = np.argsort(similarities)[-3:][::-1]
 highlighted_results = [(highlight_term(documents[i], query_str), similarities[i]) for i in sorted_indices]
 return highlighted_results

使用Hugging Face transformers庫執(zhí)行語義搜索的函數(shù)。

在semantic_searcher = pipeline("feature-extraction", model="distilbert-base-uncased")代碼片段中,有很多操作在進(jìn)行。

  • pipeline:這是從transformer庫導(dǎo)入的函數(shù),它幫助使用預(yù)訓(xùn)練的模型設(shè)置各種類型的NLP任務(wù)。
  • Feature extractio:Pipeline執(zhí)行特征提取(Feature extraction)任務(wù),將文本轉(zhuǎn)換為可用于各種下游任務(wù)的數(shù)字表示(嵌入)。
  • 用于這一任務(wù)的預(yù)訓(xùn)練模型是distilbert-base-uncased模型,它是BERT模型的一個更小、更快的版本,經(jīng)過訓(xùn)練以理解不區(qū)分大小寫的英文文本。
  • query_embedding:獲取查詢字符串的嵌入。
  • get_similarity這是一個嵌套函數(shù),用于計算查詢嵌入和文檔嵌入之間的余弦相似度。
  • doc_embeddings:獲取所有文檔的嵌入。
  • similarities:計算查詢嵌入與所有文檔嵌入之間的相似度。
  • argsort()[-3:][::-1]:按相似度降序獲取前3個相似文檔的索引。
  • highlighted_results:高亮顯示結(jié)果中的搜索詞,并存儲結(jié)果及其相似度分?jǐn)?shù)。

輸出

既然已經(jīng)了解了各種搜索技術(shù)的景,并且已經(jīng)設(shè)置了文檔以進(jìn)行搜索,現(xiàn)在看一下基于每個搜索技術(shù)的搜索查詢的輸出。

Python 
 # Main execution
 if __name__ == "__main__":
 query = input("Enter your search term: ")

 print("\nKeyword Search Results:")
 keyword_results = keyword_search(query)
 for result, score in keyword_results:
 print(f"{result} (Score: {score:.2f})")
 
 print("\nSimilarity Search Results:")
 similarity_results = similarity_search(query)
 for result, similarity in similarity_results:
 print(f"{result} (Similarity: {similarity * 100:.2f}%)")
 
 print("\nSemantic Search Results:")
 semantic_results = semantic_search(query)
 for result, similarity in semantic_results:
 print(f"{result} (Similarity: {similarity * 100:.2f}%)")

現(xiàn)在使用搜索詞“機(jī)器學(xué)習(xí)”(Machine Learning)和下面的搜索結(jié)果圖像來搜索文檔。

搜索結(jié)果中的亮點(diǎn):

(1)highlighted_results函數(shù)幫助高亮搜索詞。

(2)相似性搜索和語義搜索只返回3個結(jié)果,這是因為其代碼將這兩種搜索技術(shù)的搜索結(jié)果限制為3個。

(3)關(guān)鍵詞搜索使用TF-IDF根據(jù)文檔中相對于查詢的術(shù)語出現(xiàn)的頻率和重要性來計算分?jǐn)?shù)。

(4)相似性搜索使用向量化和余弦相似性來度量文檔在向量空間中與查詢的相似程度。

(5)語義搜索使用來自轉(zhuǎn)換器模型的嵌入和余弦相似度來捕獲文檔與查詢的語義和相關(guān)性。

(6)需要注意,由于語義搜索的強(qiáng)大功能,它檢索了與自然語言處理相關(guān)的文本,因為自然語言處理在的場景中與機(jī)器學(xué)習(xí)更為接近。

現(xiàn)在使用其他搜索詞“Artificially Intelligent”和“Artificial Intelligence”的搜索結(jié)果(需要注意,“Artificially”的拼寫錯誤是故意的),并討論結(jié)果。

搜索結(jié)果中的亮點(diǎn):

(1)搜索“人工智能”(Artificially Intelligent),由于缺乏精確或部分匹配的術(shù)語,關(guān)鍵詞搜索沒有結(jié)果。

(2)由于向量表示或相似度不匹配,相似度搜索的結(jié)果為零。

(3)語義搜索可以有效地找到場景相關(guān)的文檔,顯示出理解和匹配概念的能力,而不僅僅是精確的單詞。

(4)在第二次搜索中,拼寫錯誤的“人工智能”(Artificial Intelligence沒有正確地產(chǎn)生關(guān)鍵字搜索結(jié)果,但由于匹配的情況,其中一個文本產(chǎn)生了相似性得分。在智能、語義搜索方面,像往常一樣,從文檔中檢索到場景匹配的文本。

結(jié)論

現(xiàn)在已經(jīng)了解了各種搜索技術(shù)的性能,以下了解一些關(guān)鍵要點(diǎn):

(1)搜索方法的正確選擇應(yīng)取決于任務(wù)的要求。對任務(wù)進(jìn)行徹底的分析,并插入正確的搜索方法以獲得最佳性能。

(2)使用關(guān)鍵字搜索進(jìn)行簡單、直接的術(shù)語匹配。

(3)當(dāng)需要查找具有輕微術(shù)語變化但仍然基于關(guān)鍵字匹配的文檔時,可以使用相似度搜索。

(4)對需要深入理解內(nèi)容的任務(wù)使用語義搜索,例如在處理各種術(shù)語或需要捕獲查詢的底層含義時。

(5)還可以考慮將這些方法結(jié)合起來,以實現(xiàn)良好的平衡,利用每種方法的優(yōu)勢來提高總體性能。

(6)每種搜索技術(shù)都有進(jìn)一步優(yōu)化的余地,本文沒有對此進(jìn)行介紹。

參考文獻(xiàn)

以下參考文獻(xiàn)的文本已被這個文檔用于本文的搜索:

原文標(biāo)題:Unlocking the Power of Search: Keywords, Similarity, and Semantics Explained,作者:Pavan Vemuri


責(zé)任編輯:華軒 來源: 51CTO
相關(guān)推薦

2011-06-14 19:11:38

關(guān)鍵詞

2011-06-15 18:24:33

關(guān)鍵詞

2011-06-20 14:32:59

關(guān)鍵詞

2011-06-07 18:45:41

關(guān)鍵詞

2011-06-02 18:33:03

標(biāo)題關(guān)鍵詞

2011-06-22 19:01:54

關(guān)鍵詞

2013-08-26 15:43:40

AppStore關(guān)鍵詞開發(fā)者應(yīng)用選取關(guān)鍵詞

2011-05-17 17:47:36

關(guān)鍵詞

2011-05-10 17:53:40

網(wǎng)站優(yōu)化關(guān)鍵詞

2017-10-14 15:25:16

2011-06-14 10:01:03

長尾關(guān)鍵詞

2011-06-19 12:20:47

長尾關(guān)鍵詞

2011-05-25 17:58:00

2011-05-25 17:38:56

關(guān)鍵詞

2019-12-22 13:48:26

退休科技行業(yè)大佬

2011-06-08 09:27:45

關(guān)鍵詞

2011-06-10 14:13:24

關(guān)鍵詞

2024-06-13 09:05:12

2011-06-20 15:24:43

關(guān)鍵詞

2011-07-12 18:26:42

關(guān)鍵詞
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號