tfidf

Last-modified: 2009-02-05 (木) 23:44:30

tfidfを計算するプログラム
tfidfは,ある文章(ドキュメント)中の単語の重要度をはかる指標としてよく使われます.

定義は以下のとおり.

n = 総ドキュメント数
df(term) = termを含むドキュメント数 (Document Frequency)
tf(doc,term) = docにtermが出現する頻度(Term Frequency) そのドキュメントdocにおける単語termの引用度
idf(term) = log(n/df(term)) (inverse df) 単語termの専門性
tfidf(doc,term) = tf(doc,term)*idf(term) そのドキュメントdocにおける単語termの重要度指標

専門性の高い語がたくさん引用されていれば,そのドキュメントにおいて重要とみなされます.

以下の例では,ドキュメント番号44の文書は,たぶんスポーツカーのことを話題にしていて,「フェラーリ」「自動車」の単語がそれぞれともに5回でてきます(tf=5).しかし,dfをみると「自動車」のほうが他のたくさんの文書にもあらわれるので一般性が高いと考えられ,結果として「フェラーリ」のtfidf値のほうが高くなり,こちらの語のほうがより重要と順序づけられます.

******************************************************************************
tfidf.sas
20090205 翔
tfidfを計算するプログラム
tfidfは,ある文章(ドキュメント)中の単語の重要度をはかる指標としてよく使われます.

定義は以下のとおり.

n 総ドキュメント数
df(term) termを含むドキュメント数(Document Frequency)
tf(doc,term) docにtermが出現する頻度(Term Frequency) そのドキュメントdocにおける単語termの引用度
idf(term)=log(n/df(term)) (inverse df) 単語termの専門性
tfidf(doc,term)=tf(doc,term)*idf(term) そのドキュメントdocにおける単語termの重要度指標

専門性の高い語がたくさん引用されていれば,そのドキュメントにおいて重要とみなされます.
*******************************************************************************;

options nocenter;

/* データの準備 */
data docs;
  length doc 8;
  length term $ 40;
  input doc     /* ドキュメントの識別番号 */
       term $   /* 単語 */
  ;
 cards;
 1     モス
 1     モス
 1     ライフ
 1     ライム
 1     リサイクル
 1     リンク
 2     レジャー
 2     下調べ
 2     下調べ
;
/*略*/


proc sort data=docs;by doc term;run;

proc print data=docs(obs=100);run;


/* tfの算出 */
proc summary data=docs nway;
  class doc term;
  output out=tf(drop=_type_ rename=(_freq_=tf));
run;

/* dfの算出 */
proc summary data=tf(drop=tf) nway;
  class term;
  output out=df(drop=_type_ rename=(_freq_=df));
run;

/* nの算出 */
proc sort nodupkey data=tf out=tmp;by doc;run;
proc summary data=tmp;
  output out=n(keep=_freq_ rename=(_freq_=n));
run;


/* tfidf算出 */
proc sort data=tf;by term;run;
data tfidf;merge tf df;by term;run;
data tfidf;set tfidf;if _n_=1 then set n;

 tfidf=tf*log(n/df);

run;


proc sort data=tfidf;by doc descending tfidf;run;

proc print;by doc;run;

/*
doc=44

 term                tf    df     n      tfidf

 スポーツカー        11     3    223    47.3942
 フェラーリ           5     2    223    23.5701
 輸入                 4     3    223    17.2342
 ランボルギーニ       3     1    223    16.2215
 ポルシェ             4     4    223    16.0835
 360                  3     2    223    14.1421
 一度                 3     3    223    12.9257
 911                  2     1    223    10.8143
 ハイテクノロジー     2     1    223    10.8143
 自動車               5    30    223    10.0299
 */