gensim tfidf計算句子之間相似度

2021-09-14 08:27:41 字數 1173 閱讀 1199

def get_tfidf(words_lists):

texts = words_lists

dictionary = corpora.dictionary(texts)

feature_cnt = len(dictionary.token2id)

corpus = [dictionary.doc2bow(text) for text in texts]

tfidf = models.tfidfmodel(corpus)

return tfidf, dictionary, corpus, feature_cnt

texts:二維陣列,每一行代表乙個句子,內容是分詞結果。

dictionary:相當於建了個字典,鍵:索引,值:詞。

corpus:把句子轉化成每個詞出現多少次,[[(索引1,次數), (索引2,次數), ...],[(索引0,次數), (索引2,次數), ...]。

tfidf:以當前語料建模。

def get_semantic_similarity_for_line(words_list1, tfidf, dictionary, corpus, feature_cnt):

kw_vector = dictionary.doc2bow(words_list1)#(jieba.lcut(keyword))

index = similarities.sparsematrixsimilarity(tfidf[corpus], num_features=feature_cnt)

sim = index[tfidf[kw_vector]]

return sim

words_list1:某個句子的分詞結果。

kw_vector:相當於某個句子的corpus值,[(索引1,次數), (索引2,次數), ...]。

tfidf[corpus]:對corpus計算tfidf並轉化為[(索引1,tfidf), (索引2,tfidf), ...]。

tfidf[kw_vector]:根據doc2bow的結果直接獲取整個句子的tfidf向量,[(索引1,tfidf), (索引2,tfidf), ...]。

index:每個item代表乙個句子和其他句子的相似度。

index[tfidf[kw_vector]]:根據索引獲得某個句子與其他句子的相似度。

LASER得到句子向量,計算句子相似度

embed.sh raw.txt zh zh embeddings.raw raw.txt 未經處理的檔案 zh embeddings.raw 句子向量 假設raw.txt是中文。raw.txt是未分詞的資料,未經tokenizer.perl處理的資料,處理過程中用jieba進行分詞,並進行bpe切...

基於B gram句子概率計算實現

由於筆者所使用的語料庫是基於詞語的,所以對於詞語的計算效果更佳,但是常規句子的計算可能並不理想,建議自行尋找語料庫進行訓練。輸入為文字檔案 一句一行或者一段一行 支援批量語料輸入,可以多次或者單次呼叫addcorpus方法進行設定。訓練好之後會自行儲存模型檔案 命名為 model.txt 到專案根目...

句子語義表徵 句子向量

大體上可以分為無監督方式和監督方式 無監督句子語義表徵方法 一種最經典的方法是在one hot詞語語義表徵的基礎上使用bag of words技術。缺點 一是它丟失了詞語在句子中的順序資訊 二是它忽略了詞語的語義資訊,每個詞的one hot表徵都是等距離的。2 類似的還有用word2vec來替換on...