如何計算文本文檔相似度
計算成對相似度
確定兩個文本文檔之間相似度的最常見方法是將相似度的最常見方法是將相似度它們轉換為TF-IDF(術語頻率-逆文檔頻率)向量,然後使用餘弦相似度來比較它們。此方法在資訊檢索教科書中有所介紹,並在「資訊檢索簡介」中詳細介紹。
Gensim 和 scikit-learn 等 Python 函式庫提供了 TF-IDF 轉換和餘弦相似度計算的實作。使用scikit-learn,以下程式碼片段執行餘弦相似度計算:
<code class="python">from sklearn.feature_extraction.text import TfidfVectorizer # Extract documents from text files documents = [open(f).read() for f in text_files] # Create a TF-IDF vectorizer tfidf = TfidfVectorizer().fit_transform(documents) # Calculate pairwise cosine similarity pairwise_similarity = tfidf * tfidf.T</code>
或者,對於純文字文件:
<code class="python">corpus = ["I'd like an apple", "An apple a day keeps the doctor away", "Never compare an apple to an orange", "I prefer scikit-learn to Orange", "The scikit-learn docs are Orange and Blue"] # Create a TF-IDF vectorizer with minimum frequency and exclusion of stop words vect = TfidfVectorizer(min_df=1, stop_words="english") # Apply TF-IDF transformation tfidf = vect.fit_transform(corpus) # Calculate pairwise cosine similarity pairwise_similarity = tfidf * tfidf.T </code>
解釋結果
pairwise_similarity 為稀疏矩陣,其中每行和每列代表語料庫中的一個文件。將稀疏矩陣轉換為 NumPy 陣列表示每個單元格代表兩個對應文件之間的相似性。
例如,要確定與「The scikit-learn docs are Orange and Blue」最相似的文檔,請定位其在語料庫中的索引,然後使用np.fill_diagonal() 對角線(表示自屏蔽對角線(表示自屏蔽相似性)後將np.nanargmax 應用於對應的行:
<code class="python">import numpy as np arr = pairwise_similarity.toarray() np.fill_diagonal(arr, np.nan) input_doc = "The scikit-learn docs are Orange and Blue" input_idx = corpus.index(input_doc) result_idx = np.nanargmax(arr[input_idx]) print(corpus[result_idx])</code>
請注意,對於大型資料集,使用稀疏矩陣節省記憶體。或者,考慮使用pairwise_similarity.shape來直接掩蓋自相似性和argmax():
<code class="python">n, _ = pairwise_similarity.shape pairwise_similarity[np.arange(n), np.arange(n)] = -1.0 pairwise_similarity[input_idx].argmax() </code>
以上是如何使用 TF-IDF 和餘弦相似度計算文字文件之間的相似度?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增強效率和通用性。

theKeyDifferencesBetnewpython's“ for”和“ for”和“ loopsare:1)” for“ loopsareIdealForiteringSequenceSquencesSorkNowniterations,而2)”,而“ loopsareBetterforConterContinuingUntilacTientInditionIntionismetismetistismetistwithOutpredefinedInedIterations.un

在Python中,可以通過多種方法連接列表並管理重複元素:1)使用 運算符或extend()方法可以保留所有重複元素;2)轉換為集合再轉回列表可以去除所有重複元素,但會丟失原有順序;3)使用循環或列表推導式結合集合可以去除重複元素並保持原有順序。

fasteStmethodMethodMethodConcatenationInpythondependersonListsize:1)forsmalllists,operatorseffited.2)forlargerlists,list.extend.extend()orlistComprechensionfaster,withextendEffaster,withExtendEffers,withextend()withextend()是extextend()asmoremory-ememory-emmoremory-emmoremory-emmodifyinginglistsin-place-place-place。

toInSerteLementIntoApythonList,useAppend()toaddtotheend,insert()foreSpificPosition,andextend()formultiplelements.1)useappend()foraddingsingleitemstotheend.2)useAddingsingLeitemStotheend.2)useeapecificindex,toadapecificindex,toadaSpecificIndex,toadaSpecificIndex,blyit'ssssssslorist.3 toaddextext.3

pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)他們areStoredIncoNtiguulMemoryBlocks,mayrequireRealLealLocationWhenAppendingItems,EmpactingPerformance.2)LinkesedlistSwoldOfferefeRefeRefeRefeRefficeInsertions/DeletionsButslowerIndexeDexedAccess,Lestpypytypypytypypytypy

pythonoffersFourmainMethodStoreMoveElement Fromalist:1)刪除(值)emovesthefirstoccurrenceofavalue,2)pop(index)emovesanderturnsanelementataSpecifiedIndex,3)delstatementremoveselemsbybybyselementbybyindexorslicebybyindexorslice,and 4)

toresolvea“ dermissionded”錯誤Whenrunningascript,跟隨台詞:1)CheckAndAdjustTheScript'Spermissions ofchmod xmyscript.shtomakeitexecutable.2)nesureThEseRethEserethescriptistriptocriptibationalocatiforecationAdirectorywherewhereyOuhaveWritePerMissionsyOuhaveWritePermissionsyYouHaveWritePermissions,susteSyAsyOURHomeRecretectory。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

記事本++7.3.1
好用且免費的程式碼編輯器

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。