经过之前的文本处理步骤后,我们得到了一个从令牌到数字的映射表 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∣{t∈d}+1∣D∣)
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)=∣d∣count(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
中。