利用 TF-IDF 和Word Counts构建基础模型

本文介绍了一种改进的TF-IDF算法,通过数字规范化处理降低维度,并使用停用词表提高文本特征提取的效率。文章详细展示了如何利用自定义的NumberNormalizingVectorizer类进行文本预处理,同时对比了CountVectorizer的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

TF-IDF

def number_normalizer(tokens):
    """ 将所有数字标记映射为一个占位符(Placeholder)。
    对于许多实际应用场景来说,以数字开头的tokens不是很有用,
    但这样tokens的存在也有一定相关性。 通过将所有数字都表示成同一个符号,可以达到降维的目的。
    """
    return ("#NUMBER" if token[0].isdigit() else token for token in tokens)


class NumberNormalizingVectorizer(TfidfVectorizer):
    def build_tokenizer(self):
        tokenize = super(NumberNormalizingVectorizer, self).build_tokenizer()
        return lambda doc: list(number_normalizer(tokenize(doc)))
# 利用刚才创建的NumberNormalizingVectorizer类来提取文本特征,注意里面各类参数的含义,自己去sklearn官方网站找教程看
# 停用词可以采用 baidu停用词表
stwlist=[line.strip() for line in open('/home/kesci/input/stopwords7085/停用词汇总.txt',
'r',encoding='utf-8').readlines()]
tfv = NumberNormalizingVectorizer(min_df=3,  
                                  max_df=0.5,
                                  max_features=None,                 
                                  ngram_range=(1, 2), 
                                  use_idf=True,
                                  smooth_idf=True,
                                  stop_words = stwlist)

# 使用TF-IDF来fit训练集和测试集(半监督学习)
tfv.fit(list(xtrain) + list(xvalid))
xtrain_tfv =  tfv.transform(xtrain) 
xvalid_tfv = tfv.transform(xvalid)

CountVectorizer

ctv = CountVectorizer(min_df=3,
                      max_df=0.5,
                      ngram_range=(1,2),
                      stop_words = stwlist)

# 使用Count Vectorizer来fit训练集和测试集(半监督学习)
ctv.fit(list(xtrain) + list(xvalid))
xtrain_ctv =  ctv.transform(xtrain) 
xvalid_ctv = ctv.transform(xvalid)

后续可以用 LogisticRegression , 朴素贝叶斯,支持向量机(SVM),xgboost 来进行后续的fit

### TF-IDF算法的使用方法与实现方式 #### 什么是TF-IDFTF-IDF是一种用于评估一个词在一个文档集或者语料库中的重要程度的方法。它由两部分组成: - **TF (Term Frequency)** 表示某个词在当前文档中出现的频率[^2]。 - **IDF (Inverse Document Frequency)** 表示这个词在整个文档集中出现的逆向频率,用来降低常见词的影响。 最终计算公式如下: \[ \text{TF-IDF}(t, d, D) = \text{TF}(t, d) \times \text{IDF}(t, D) \] 其中 \( t \) 是目标词,\( d \) 是单个文档,\( D \) 是整个文档集合。 --- #### Python实现TF-IDF算法 以下是基于Python的一个简单实现: ```python from sklearn.feature_extraction.text import TfidfVectorizer # 文档数据 corpus = [ 'This is the first document.', 'This document is the second document.', 'And this is the third one.', 'Is this the first document?' ] # 初始化TfidfVectorizer对象 vectorizer = TfidfVectorizer() # 计算TF-IDF矩阵 X = vectorizer.fit_transform(corpus) # 获取特征名称(即词汇表) feature_names = vectorizer.get_feature_names_out() # 输出TF-IDF矩阵及其对应的词汇 print("Vocabulary:", feature_names) print("\nTF-IDF Matrix:\n", X.toarray()) ``` 此代码片段展示了如何使用 `sklearn` 库快速构建TF-IDF模型并获取结果。每行代表一个文档,列则对应于不同的单词,数值表示相应单词的TF-IDF得分[^1]。 --- #### 自定义实现TF-IDF 如果不借助第三方库,可以手动编写TF-IDF函数: ```python import math from collections import Counter def compute_tf(text_list): """计算TF""" tf_dict = {} for text in text_list: counts = Counter(text.split()) # 统计每个词频次 total_words = sum(counts.values()) word_tfs = {word: count / total_words for word, count in counts.items()} tf_dict[text] = word_tfs return tf_dict def compute_idf(text_list): """计算IDF""" idf_dict = {} N = len(text_list) all_words = set(word for text in text_list for word in text.split()) for word in all_words: doc_count = sum(1 for text in text_list if word in text.split()) idf_dict[word] = math.log(N / (doc_count + 1)) # 防止除零错误 return idf_dict def compute_tfidf(tf_dict, idf_dict): """计算TF-IDF""" tfidf_dict = {} for text, tf_values in tf_dict.items(): tfidf_scores = {word: tf * idf_dict.get(word, 0) for word, tf in tf_values.items()} tfidf_dict[text] = tfidf_scores return tfidf_dict # 测试数据 texts = ["this is a test", "another test with some words"] tf_result = compute_tf(texts) idf_result = compute_idf(texts) tfidf_result = compute_tfidf(tf_result, idf_result) for text, scores in tfidf_result.items(): print(f"Text: '{text}' -> Scores: {scores}") ``` 这段代码实现了完整的TF-IDF逻辑,包括词频统计、逆文档频率以及两者结合后的权重计算[^3]。 --- #### 结果解释 通过上述两种方法,可以获得各个文档中词语的重要度评分。高分意味着该词对该文档具有较高的区分能力,而低分通常表明它是通用词汇或不重要的内容。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值