偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

解鎖搜索的力量:關鍵詞、相似性和語義解釋

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

譯者 | 李睿

審校 | 重樓

深入研究不同的搜索技術

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

首先看看程序使用的標準代碼組件。

1.使用的標準代碼組件

A.導入的庫

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

在這個塊中導入了以下必要的庫:

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

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. "
 ]

定義一個示例文檔列表,其中包含與人工智能、機器學習和自然語言處理中的各種主題相關的文本。

C.高亮功能

Python 

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

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

2.關鍵字搜索

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

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

A.關鍵字搜索如何工作

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

B.檢查關鍵字搜索背后的代碼

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í)行關鍵字搜索。

Schema和TEXT采用單個字段內容定義模式。

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

將在本文后面檢查關鍵字搜索輸出和其他搜索技術。

3.相似性搜索

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

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

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

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

4.語義搜索

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

A.語義搜索如何工作

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

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")代碼片段中,有很多操作在進行。

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

輸出

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

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)在使用搜索詞“機器學習”(Machine Learning)和下面的搜索結果圖像來搜索文檔。

搜索結果中的亮點:

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

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

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

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

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

(6)需要注意,由于語義搜索的強大功能,它檢索了與自然語言處理相關的文本,因為自然語言處理在的場景中與機器學習更為接近。

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

搜索結果中的亮點:

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

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

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

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

結論

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

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

(2)使用關鍵字搜索進行簡單、直接的術語匹配。

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

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

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

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

參考文獻

以下參考文獻的文本已被這個文檔用于本文的搜索:

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


責任編輯:華軒 來源: 51CTO
相關推薦

2011-06-14 19:11:38

關鍵詞

2011-06-15 18:24:33

關鍵詞

2011-06-20 14:32:59

關鍵詞

2011-06-07 18:45:41

關鍵詞

2011-06-02 18:33:03

標題關鍵詞

2011-06-22 19:01:54

關鍵詞

2013-08-26 15:43:40

AppStore關鍵詞開發(fā)者應用選取關鍵詞

2011-05-10 17:53:40

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

2011-05-17 17:47:36

關鍵詞

2017-10-14 15:25:16

2011-06-19 12:20:47

長尾關鍵詞

2011-06-14 10:01:03

長尾關鍵詞

2019-12-22 13:48:26

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

2011-05-25 17:38:56

關鍵詞

2011-05-25 17:58:00

2011-06-08 09:27:45

關鍵詞

2011-06-10 13:34:17

關鍵詞

2011-07-06 18:18:01

關鍵詞密度

2011-07-12 18:26:42

關鍵詞

2011-06-10 14:13:24

關鍵詞
點贊
收藏

51CTO技術棧公眾號