私はcsvファイルに保存された重複ドキュメントペアのリストを持っています。既知の重複ペアのコサイン類似度
Document_ID1 Document_ID2
12345 87565
34546 45633
56453 78645
35667 67856
13636 67845
各ドキュメントIDがどこか別の場所に保存されたテキストに関連付けられている:1列目からの各IDには、ファイルはこのような何かを行く列2 の対応するIDと重複しています。私はこのテキストを引っ張ってIDの各列と関連するテキストを2つのlsmデータベースに保存しました。
は、だから私は値それぞれのキーのとしてDocument_ID1
などのキーと、それに対応するテキストからすべてのIDを持っているdb1
を持っています。したがって、辞書のように。同様に、すべてのIDがDocument_ID2
の場合はdb2
です。
だから、私はdb1[12345]
を言うとき、私はID今12345
に関連付けられたテキストを取得し、私は彼らの重複ネスを決定するためにこれらの対のそれぞれの間のコサイン類似性スコアを取得したいです。これまでは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行が取得されます。
私が望むのは、db1の対応するキーのコサイン類似度スコアをdb2のキーにすることです。つまり、db1とdb2にそれぞれ5つのキーがある場合は、結果として5行しか持たないはずです。つまり、各ペアの重複のコサイン類似度だけです。
これを取得するために私のコードを調整する必要がありますか?