python - 计算 pandas 中的 Tf-Idf 分数?

标签 python python-3.x pandas tf-idf tfidfvectorizer

我想从下面的文档中单独计算 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/

相关文章:

python - 字符串列表时如何按第一列将二维数组排序为数字? (Python)

python - 属性错误 : 'str' object has no attribute 'policy'

python - Pandas 分组

pandas - 按时间间隔内花费的最多时间标记行

python - 在 Mac 上安装 python 模块最兼容的方式是什么?

python - Keras 模型无法使用 TFRecordDataset 作为输入来预测新样本

python-3.x - 维度不匹配 : array 'cov' is of shape (1, 1),但 'mean' 是长度为 2 的向量

python - 如何使用 PYTHON 的 mysql-connector 将 MySQL 数据库导出为 json?

python - 在 pandas/python 中,读取存储为字符串的数组

python - PySpark 相当于 Pandas UDF 中的 lambda 函数