2017-08-25 90 views
0

我有一個分組DF:TfidfVectorizer與ID重複返回0的n-gram在熊貓DF

id text 
100 he loves ice cream 
100 she loves ice 
100 i hate avocado 

我提取二元語法,頻率和TFIDF分數具有這種功能:

def extractFeatures(groupedDF, textCol): 
    features = pd.DataFrame() 
    for id, group in tqdm(groupedDF): 
      freq = cv.fit_transform(group[textCol]) 
      tfidf = tv.fit_transform(group[textCol]) 
      freq = sum(freq).toarray()[0] 
      tfidf.todense() 
      tfidf = tfidf.toarray()[0] 
      freq = pd.DataFrame(freq, columns=['frequency']) 
      tfidf = pd.DataFrame(tfidf, columns=['tfidf']) 
      dfinner = pd.DataFrame(cv.get_feature_names(), columns=['ngram']) 
      dfinner['id'] = id 
      dfinner = dfinner.join(freq) 
      results = dfinner.join(tfidf) 
      features = features.append(results) 
    return features 

此結果在以下df中:

id ngram   frequency tfidf 
100 hate avocado 1   0 
100 he loves  1   .3 
100 i hate  1   0 
100 ice cream  1   .3 
100 loves ice  2   .6 
100 she loves  1   0 

tfidf分數是人爲設計的。所以,該功能正確地找到頻率。然後找到第一排分組df的tfidf分數(包括出現在多行中的bigram);最後,它找不到第二排和第三排唯一的bigrams的tfidf分數。 ,而tfidf分數是設計出來的,對於任何在特定文檔中具有相同頻率的二元組來說,它們是相同的,因此,第一行中頻率爲1的任何二元組將具有.3 tfidf分數。 。與1另一行可能有。24一TFIDF分數頻率這很奇怪,因爲每個兩字的詞頻肯定是不同的

兩個問題:

  1. 爲什麼沒有找到第二行和第三行的tfidf分數?
  2. 爲什麼tfidf分數對於在特定文檔中出現在相同頻率的特定bigram是相同的?

謝謝任何​​你可能有的見識!

回答

0
print(df) 

    id text 
0 100 he loves ice cream 
1 100 she loves ice 
2 100 i hate avocado 

TF-IDF計算爲一個字相比文檔的其餘部分,其相對於一個字中的一個文檔中的頻率的重要性。如果要計算TF-IDF,我會建議使用scikit學習TfidfVectorizer()

from sklearn.feature_extraction.text import TfidfVectorizer 

vectorizer = TfidfVectorizer(smooth_idf=True, 
          ngram_range = (2,2), 
          token_pattern='(?u)\\b\\w\\w*\\b'              
          ) 

words = vectorizer.fit_transform(df.text) 

df2 = pd.DataFrame(words.todense()).rename(columns=dict(zip(vectorizer.vocabulary_.values(), 
vectorizer.vocabulary_.keys()))) 

print(df2) 

    hate avocado he loves i hate  ice cream loves ice she loves 
0 0.000000 0.622766 0.000000 0.622766 0.473630 0.000000 
1 0.000000 0.000000 0.000000 0.000000 0.605349 0.795961 
2 0.707107 0.000000 0.707107 0.000000 0.000000 0.000000 

上面的矩陣給出了每個文檔的每個單詞的相對重要性,如果這個詞沒有在文檔中出現它的價值是零。

您還可以使用scikit-learn CountVectorizer()以相同的方式計算頻率