
自定义 tf-idf 计算,避免词组拆分
在使用 tfidfvectorizer 计算 tf-idf 值时,当文本数据包含词组时,可能会遇到自动分词的问题,导致输出特征包含分拆后的单词。为了解决这一问题,以下提供两种方法:
1. 调整 tfidfvectorizer 参数
如果文本数据中的词组由下划线或其他字符连接,可以设置 tfidfvectorizer 的 analyzer 参数为 "word",以禁用分词功能。
from sklearn.feature_extraction.text import tfidfvectorizer docs = ["this_is_book", "this_is_apple"] vectorizer = tfidfvectorizer(analyzer="word", stop_words="english") tfidf = vectorizer.fit_transform(docs) print(vectorizer.get_feature_names_out())
输出:
['this_is_apple', 'this_is_book']
2. 自定义 tf-idf 计算
如果你不想使用 tfidfvectorizer,也可以自行编写 tf-idf 计算程序。以下是一个示例实现:
import math
def tfidf_custom(docs, vocab):
"""
自定义 TF-IDF 计算
参数:
docs: 文档集合
vocab: 词汇表
"""
# 计算词频
tf_dict = {}
for doc in docs:
for word in doc:
if word in tf_dict.keys():
tf_dict[word] += 1
else:
tf_dict[word] = 1
# 计算文档频率
df_dict = {}
for word in vocab:
for doc in docs:
if word in doc:
if word in df_dict.keys():
df_dict[word] += 1
else:
df_dict[word] = 1
# 计算 TF-IDF 值
tfidf_dict = {}
for word in vocab:
tfidf_dict[word] = (tf_dict[word] / sum(tf_dict.values())) * math.log(len(docs) / df_dict[word])
return tfidf_dict
# 文档集合和词汇表
docs = ["This_is_book", "This_is_apple"]
vocab = ["This_is_apple", "This_is_book"]
tfidf_custom(docs, vocab)以上就是如何避免词组拆分影响 TF-IDF 计算?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号