NLP 从零开始实现 词袋(BOW) 和 TFIDF 文本表示模型(二)

本文介绍了一种将文本转换为数字向量的方法,包括创建词汇表、计算词频及TF-IDF值,用于文本分析和信息检索。

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

经过之前的文本处理步骤后,我们得到了一个从令牌到数字的映射表 word_to_int。下面我们就用这个映射表,将 语料库 中的每个文本用一个相同长度的数字向量表示。

假设我们语料库中的某个文本为:Undocumented Catalina file access change,经过预处理后得到一个令牌向量:['undocu', 'catalina', 'file', 'access', 'chang']

六:计算词频率
# 将每个文档转化为长度为 词袋总数的向量,值为词出现的频率,例如['a', 'b', 'a'] 转化为 
# 					a	b
# ['a', 'b', 'a']	2	1
one_hot_corpus = []
for nc in new_corpus:
	# 将每个 令牌 映射为 整数
    int_words = [word_to_int[w] for w in nc]
    
    # 初始化一个长度为 令牌总数的,初始值为 0 的向量
    one_hot_text = [0] * len(unique_words)
    for pos in int_words:
    	# 以映射的整数为下标,计算对应词出现的频率
        one_hot_text[pos] += 1
    one_hot_corpus.append(one_hot_text)

得到每个文本的词频后,下面开始计算每个位置的逆文档频率(TFIDF

七:计算 IDF

使用公式:
i d f ( t , d , D ) = l o g ( ∣ D ∣ ∣ d ∣ { t ∈ d } + 1 ) idf(t,d, D) = log(\frac{|D|}{|d|\{t \in d\} + 1}) idf(t,d,D)=log(d{td}+1D)

one_hot_corpus_np = np.array(one_hot_corpus)
word_idf = []

# 文档总数
doc_count = one_hot_corpus_np.shape[0]

for word in word_to_int.values():
    # 包含 word 的文档总数
    word_doc_count = len([i for i in one_hot_corpus_np[:, word] if i > 0])
    word_idf.append(np.log((doc_count/word_doc_count + 1)))
八:计算 tfidf

使用公式:
t f i d f ( t , d , D ) = t f ( t , d ) ∗ i d f ( t , d , D ) tfidf(t,d,D) = tf(t,d) * idf(t, d, D) tfidf(t,d,D)=tf(t,d)idf(t,d,D)
t f ( t , d ) = c o u n t ( t , d ) ∣ d ∣ tf(t,d)=\frac{count(t,d)}{|d|} tf(t,d)=dcount(t,d)

# tfidf
tfidf_corpus = []

for text in one_hot_corpus_np:
    # 文档词频
    word_freq = text/sum(text)
    tfidf_corpus.append(word_freq * word_idf)

到此,即得到了用tfidf文本模型表示的语料库,存储在 tfidf_corpus 中。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值