【发布时间】:2019-09-28 03:41:38
【问题描述】:
所以我有下表,每一行是一个文档,每一列是单词,没有单词出现。
|doc|apple|banana|cat|
|---|---|---|---|
|1|2|0|0|
|2|0|0|2|
|3|0|2|0|
有什么方法可以将这些计数矢量化表转换为 tf-idf 矢量化器?
编辑:我的解决方案。让我知道这是否正确。
def get_tfidf(df_tfidf):
total_docs = df_tfidf.shape[0]
#Term Frequency
#(Number of times term w appears in a document) / (Total number of
#terms in the document)
total_words_doc = df_tfidf.astype(bool).sum(axis=1)
tf = df_tfidf.values/total_words_doc[:,None]
#Inverse document frequency
#log_e(Total number of documents / Number of documents with term w in
#it)
words_in_doc = df_tfidf.astype(bool).sum(axis=0)
idf = np.log(total_docs/words_in_doc)
tf_idf = tf*idf.values[None,:]
return tf_idf
【问题讨论】:
标签: python pandas machine-learning