2017-04-20 25 views
0

我有保存在csv文件中的重複文檔對的列表。從第1列每個ID是重複的,以相應的ID列2 該文件是這樣的:已知成對副本的餘弦相似度

Document_ID1 Document_ID2 
12345   87565 
34546   45633 
56453   78645 
35667   67856 
13636   67845 

每個文檔ID與保存在其他地方的文本關聯。我拉下這段文字,並將每一列ID和相關文本保存到兩個lsm數據庫中。
所以我有db1其中Document_ID1的所有ID爲及其相應的文本作爲爲各自的鍵。因此,就像字典一樣。同樣,db2來自Document_ID2的所有ID。
所以,當我說db1[12345],我得到了ID 12345

現在,我想這些對之間的餘弦相似性指標,以確定其重複岬相關的文本。到現在爲止,我運行了一個tfidf模型來做同樣的事情。我創建了一個包含db1中所​​有文檔的tfidf矩陣作爲語料庫,並且我測量了來自db2的每個tfidf向量與tfidf矩陣的餘弦相似度。出於安全原因,我無法提供完整的代碼。代碼是這樣的:

# Generator function to pick one key (document) at a time for comparison against other documents 
def generator(db): 
    for key in db.keys(): 
     text = db[key] 
     yield text 

# Use spaCy to create a function to preprocess text from the generator function 
nlp = spacy.load('en') 
def spacy(generator_object): 
    for doc in generator_object: 
     words = <code to make words lower case, remove stop words, spaces and punctuations> 
     yield u' '.join(words) 

# TF-IDF Vectorizer 
tfidf = TfidfVectorizer(min_df = 2) 

# Applying tf-idf transformer to each key from db1 individually in the generator function. 
tfidf_matrix = tfidf.fit_transform(spacy(generator(db1))) 

# Function to calculate cosine similarity values between the tfidf matrix and the tfidf vector of a new key 
def similarity(tfidf_vector, tfidf_matrix, keys):  
    sim_vec = <code to get cosine similarity> 
    return sim_vec.sort_values(ascending=False) 

# Applying tf-idf transformer on db2 keys on a loop and getting cosine similarity scores for each key from db2. 
for key in db2.keys(): 
    # Create a new temporary db for each key from db2 to enter into generator function 
    new = <code to create a temporary new lsm database> 
    text = db2[key] 
    new[key] = text 
    new_key = <code to get next key from the temporary new lsm database> 
    tfidf_vector = tfidf.transform(spacy_proc(corpus_gen(new))) 
    similarity_values = similarity(tfidf_vector, tfidf_matrix, list(db1.keys())) 
    for idx, i in similarity_values.iteritems(): 
      print new_key, idx, i 
    del new[key] 

但是這給了我反對在DB2每個鍵在DB1所有按鍵餘弦相似度得分。示例:如果db1中有5個鍵,db2中有5個鍵,則此代碼會得到25行。
我想要的是從db1中爲db2中的鍵獲取相應的鍵的餘弦相似性分數。這意味着如果db1和db2中的每個鍵都有5個鍵,那麼我應該只有5行作爲結果 - 僅用於每對重複項的餘弦相似性分數。

我應該如何調整我的代碼來獲取?

回答

0

因爲還沒有確定的答案,所以我得到了所有行的數據框(上面的例子中有25行結果),並且內部連接/合併了一個數據幀,該數據幀具有重複對列表(即我需要的5行輸出)。這樣,結果數據幀就具有重複文檔對的相似性分數。 這是一個臨時解決方案。如果任何人都能想出一個更清潔的解決方案,我會接受這個答案作爲答案。