如何避免词组拆分影响 TF-IDF 计算?
一分耕耘,一分收获!既然都打开这篇,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新文章相关的内容,希望对大家都有所帮助!

自定义 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 计算? 》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注米云公众号!
