使用已知 python 包来实现 N-Gram、TF-IDF 和余弦相似度

Using known python packages for implementing N-Gram, TF-IDF and Cosine similarity

我正在尝试使用

实现相似度函数

例子

概念:

words = [...]
word = '...'
similarity = predict(words,word)

def predict(words,word):
     words_ngrams = create_ngrams(words,range=(2,4))  
     word_ngrams =  create_ngrams(word,range=(2,4))

     words_tokenizer = tfidf_tokenizer(words_ngrams)
     word_vec = words_tokenizer.transform(word)

     return cosine_similarity(word_ved,words_tokenizer)

我在网上搜索了一种简单而安全的实现方式,但找不到使用 已知 python 软件包 as sklearn、nltk、scipy等
他们中的大多数使用 "self made" 计算。

我尽量避免每一步都手动编码,我猜有一个简单的解决方法可以解决所有 'that pipeline'。

任何帮助(和代码)将不胜感激。发送:)

最终我想通了...

如果有人会发现这个问题需要解决方案,这里是我编写的一个函数来处理它...

'''
### N-Gram & TD-IDF & Cosine Similarity
Using n-gram on 'from column' with TF-IDF to predict the 'to column'.
Adding to the df a 'cosine_similarity' feature with the numeric result.
'''
def add_prediction_by_ngram_tfidf_cosine( from_column_name,ngram_range=(2,4) ):
    global df
    from sklearn.feature_extraction.text import TfidfVectorizer
    from sklearn.metrics.pairwise import cosine_similarity
    vectorizer = TfidfVectorizer( analyzer='char',ngram_range=ngram_range )
    vectorizer.fit(df.FromColumn)

    w = from_column_name
    vec_word = vectorizer.transform([w])

    df['vec'] = df.FromColumn.apply(lambda x : vectorizer.transform([x]))
    df['cosine_similarity'] = df.vec.apply(lambda x : cosine_similarity(x,vec_word)[0][0])

    df = df.drop(['vec'],axis=1)

注意:它还没有生产就绪