csv 파일에 저장된 중복 문서 쌍 목록이 있습니다. 1 열에서 각 ID는 파일이 이런 식 2 열 에서 해당 ID에 중복 :이미 알려진 쌍의 코사인 유사도
Document_ID1 Document_ID2
12345 87565
34546 45633
56453 78645
35667 67856
13636 67845
각 문서 ID가 다른 곳에 저장되고 텍스트와 연결되어 있습니다. 나는이 텍스트를 꺼내 ID와 관련 텍스트의 각 컬럼을 두 개의 lsm 데이터베이스에 저장했다.
그래서 나는 값을 각각의 키에 대한로 키 및 해당 텍스트로 Document_ID1
의 모든 ID를 가지고 db1
있습니다. 따라서 사전처럼. 마찬가지로 모든 ID가 Document_ID2
인 경우 db2
입니다. 내가 db1[12345]
말할 때
그래서, 나는 12345
지금, 나는 그들의 중복 다움을 확인하려면 다음 각 쌍 사이의 코사인 유사도 점수를 얻을하고자하는 ID와 연관된 텍스트를 얻을. 지금까지는 tfidf 모델을 실행하여 동일한 작업을 수행했습니다. 나는 db1에있는 모든 문서를 코퍼스로 사용하여 tfidf 행렬을 만들었고 tfidf 행렬에 대해 db2의 각 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 개의 행을 얻습니다.
내가 원하는 것은 DB2의 키에 대해 db1의 해당 키에 대한 코사인 유사성 점수를 얻는 것입니다. 즉, db1과 db2에 각각 5 개의 키가있는 경우 결과적으로 5 개의 행만 가져야합니다. 각 쌍의 코사인 유사성 스코어가 있어야합니다.
어떻게 코드를 수정해야합니까?