我想从下面的文档中单独计算 tf 和 idf 。我正在使用 python 和 pandas。
import pandas as pd
df = pd.DataFrame({'docId': [1,2,3],
'sent': ['This is the first sentence','This is the second sentence', 'This is the third sentence']})
我想使用 Tf-Idf 公式进行计算,而不是使用 Sklearn 库。
标记化后,我用它来计算 TF:
tf = df.sent.apply(pd.value_counts).fillna(0)
但这给了我一个计数,但我想要(计数/单词总数)的比率
。
对于以色列国防军:
df[df['已发送'] > 0]/(1 + len(df['已发送'])
但似乎不起作用。 我想要 Tf 和 Idf 都作为 pandas 系列格式。
编辑
对于标记化,我使用了df['sent'] = df['sent'].apply(word_tokenize)
我得到的 idf 分数为:
tfidf = TfidfVectorizer()
feature_array = tfidf.fit_transform(df['sent'])
d=(dict(zip(tfidf.get_feature_names(), tfidf.idf_)))
如何单独获取 tf 分数?
最佳答案
您需要做更多的工作来计算这个。
import numpy as np
df = pd.DataFrame({'docId': [1,2,3],
'sent': ['This is the first sentence',
'This is the second sentence',
'This is the third sentence']})
# Tokenize and generate count vectors
word_vec = df.sent.apply(str.split).apply(pd.value_counts).fillna(0)
# Compute term frequencies
tf = word_vec.divide(np.sum(word_vec, axis=1), axis=0)
# Compute inverse document frequencies
idf = np.log10(len(tf) / word_vec[word_vec > 0].count())
# Compute TF-IDF vectors
tfidf = np.multiply(tf, idf.to_frame().T)
print(tfidf)
is the first This sentence second third
0 0.0 0.0 0.095424 0.0 0.0 0.000000 0.000000
1 0.0 0.0 0.000000 0.0 0.0 0.095424 0.000000
2 0.0 0.0 0.000000 0.0 0.0 0.000000 0.095424
根据您的情况,您可能需要标准化:
# L2 (Euclidean) normalization
l2_norm = np.sum(np.sqrt(tfidf), axis=1)
# Normalized TF-IDF vectors
tfidf_norm = (tfidf.T / l2_norm).T
print(tfidf_norm)
is the first This sentence second third
0 0.0 0.0 0.308908 0.0 0.0 0.000000 0.000000
1 0.0 0.0 0.000000 0.0 0.0 0.308908 0.000000
2 0.0 0.0 0.000000 0.0 0.0 0.000000 0.308908
关于python - 计算 pandas 中的 Tf-Idf 分数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51651942/