简体   繁体   中英

sklearn : TFIDF Transformer : How to get tf-idf values of given words in document

I used for calculating TFIDF (Term frequency inverse document frequency) values for documents using command as :计算文档的 TFIDF(术语频率逆文档频率)值,使用命令为:

from sklearn.feature_extraction.text import CountVectorizer
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(documents)
from sklearn.feature_extraction.text import TfidfTransformer
tf_transformer = TfidfTransformer(use_idf=False).fit(X_train_counts)
X_train_tf = tf_transformer.transform(X_train_counts)

X_train_tf is a scipy.sparse matrix of shape (2257, 35788) .

How can I get TF-IDF for words in a particular document? More specific, how to get words with maximum TF-IDF values in a given document?

You can use TfidfVectorizer from sklean

from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
from scipy.sparse.csr import csr_matrix #need this if you want to save tfidf_matrix

tf = TfidfVectorizer(input='filename', analyzer='word', ngram_range=(1,6),
                     min_df = 0, stop_words = 'english', sublinear_tf=True)
tfidf_matrix =  tf.fit_transform(corpus)

The above tfidf_matix has the TF-IDF values of all the documents in the corpus. This is a big sparse matrix. Now,

feature_names = tf.get_feature_names()

this gives you the list of all the tokens or n-grams or words. For the first document in your corpus,

doc = 0
feature_index = tfidf_matrix[doc,:].nonzero()[1]
tfidf_scores = zip(feature_index, [tfidf_matrix[doc, x] for x in feature_index])

Lets print them,

for w, s in [(feature_names[i], s) for (i, s) in tfidf_scores]:
  print w, s

Here is another simpler solution in Python 3 with pandas library

from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd

vect = TfidfVectorizer()
tfidf_matrix = vect.fit_transform(documents)
df = pd.DataFrame(tfidf_matrix.toarray(), columns = vect.get_feature_names())
print(df)

Finding tfidf score per word in a sentence can help in doing downstream task like search and semantics matching.

We can we get dictionary where word as key and tfidf_score as value.

from sklearn.feature_extraction.text import TfidfVectorizer

tfidf = TfidfVectorizer(min_df=3)
tfidf.fit(list(subject_sentences.values()))
feature_names = tfidf.get_feature_names()

Now we can write the transformation logic like this

def get_ifidf_for_words(text):
    tfidf_matrix= tfidf.transform([text]).todense()
    feature_index = tfidf_matrix[0,:].nonzero()[1]
    tfidf_scores = zip([feature_names[i] for i in feature_index], [tfidf_matrix[0, x] for x in feature_index])
    return dict(tfidf_scores)

Eg For a input

text = "increase post character limit"
get_ifidf_for_words(text)

output would be

{
'character': 0.5478868741621505,
'increase': 0.5487092618866405,
'limit': 0.5329156819959756,
'post': 0.33873144956352985
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM