【Python机器学习】NLP词中的数学——词袋

我们已经收集了一些词/词条,对这些词进行计数,并将它们归并成词干或者词元,接下来就可以做更多的事情。分析词对一些简单的任务有用,例如得到词用法的一些统计信息,或者进行关键词检索。但如果我们想知道哪些词对于某篇文档和整个语料库更重要。于是,我们可以利用这个“重要度”值,基于文档内的关键词重要度在语料库中寻找相关文档。

这样做的话,会使我们的应用更不可能受限于单个或少数几个特殊的词。也因为有较大范围的词都带有不同程度的得分或变迁,因为我们可以度量一条文档的某个类别的程度。如果知道一些词在某个文档相对于剩余文档的频率,就可以利用这个信息来进一步修正文档的正向程度。

当我们构建了文本的向量空间模型。我们使用了每个词的独热向量,然后将所有这些向量用二进制OR运算(或者截断和)组合以创建文本的向量表示。如果被加载到一个诸如Pandas DataFrame的数据结构中,这种二值的词袋向量也可以为文档检索提供一个很棒的索引。

加下来考虑一个更有用的向量表示方法,它计算词在给定文本中的出现次数和频率。这里引入第一个近似假设,假设一个词在文档中出现的次数越多,那么该词对文档的意义的贡献就越大。相比于多次提到“cats”和“gravity”的文档,一篇多次提到“wings”和“rudder”的文档可能会与涉及喷气式飞机或者航空旅行的主题更相关。或者我们给出了很多表达正向情感的词,比如good、best、joy等,一篇文档包含的这类词越多,就认为它越可能包含了正向情感。但是可以想象,一个只依赖这些简单规则的算法可能会出错或者误导用户。

下面给出了一个统计次出现次数很有用的例子:

from nltk.tokenize import TreebankWordTokenizer
from collections import Counter

sentence="""
The faster Harry got to the store, the faster Harry, the faster, would get home.
"""
tokenizer=TreebankWordTokenizer()
tokens=tokenizer.tokenize(sentence.lower())
print(tokens)
bag_of_words=Counter(tokens)
print(bag_of_words)

上述代码中,通过引入list,将文档中得到独立的词及其出现的次数。Python的字典可以很好的实现这一目标,由于同时要对词计数,因此可以使用Counter。

使用Python中任意一种较好的字典实现,键的词序都会发生变换。新的词序针对存储、更新和检索做了优化,而不是为了保持显示的一致性,包含在原始语句词序中的信息内容被忽略。

像上面这样的短文档,无需的词袋仍然包含了句子的原本意图中的很多信息。这些词袋中的信息对于有些任务已经足够强大,这些任务包括垃圾邮件检测、情感(倾向性、满意度等)计算甚至一些微妙意图(如讽刺检测)的检测。虽然只是一个词袋,但是它装满了意义和信息。因此,下面我们将这些词按照某种方式进行排序,以便能够对此有所了解。

Counter对象有一个很方便的方法,可以实现上述目标:

print(bag_of_words.most_common(4))

这里给出了从高到低频率的前4个词条。

具体来说,某个词在给定文档中出现的次数称为词项频率(简写为TF)。在某些例子中,可以将某个词的出现频率除以文档中的词项总数从而得到归一化的词项频率结果。

在上面的例子中,排名最靠前的4个词/词条分别是“the”、“,”、“harry”、“faster”,但是“the”、“,”这两个对于文档的意图而言信息量不大,并且这些信息量不大的词条可能会在我们的快速探索之旅中多次出现。我们要在排名靠前的词项频率向量(词袋)中留下“harry”和“faster”这两个词条。

下面是在Counter对象中计算“harry”的词频:

times_harry_appears=bag_of_words['harry']
num_unique_words=len(bag_of_words)
tf=times_harry_appears/num_unique_words
print(round(tf,4))

归一化词项频率是经过文档长度“调和”后的词频,比如在两篇文档中cat出现的频率:

  • TF("cat",dac_a)=3/30=0.1
  • TF("cat",dac_b)=100/20000=0.005

可以看到,虽然文档B中“cat”出现次数多,但文档更长,所以频率低,相比来说,“cat”对于文档A更重要。

因此,我们不使用原始的词频来描述语料库中的文档,而使用归一化词项频率。类似地,我们可以计算每个词对文档的相对重要程度。我们已经做了很多工作奖文本转换成数值,而且超越了仅表示特特定词出现与否的范围。

下面考虑一个更长的文本片段:

from collections import Counter
from nltk.tokenize import TreebankWordTokenizer
tokenizer=TreebankWordTokenizer()
kite_txt="""
A kite is traditionally a tethered heavier-than-air craft with wing surfaces that react against the air to create lift and drag. A kite consists of wings, tethers, and anchors. Kites often have a bridle to guide the face of the kite at the correct angle so the wind can lift it. A kite’s wing also may be so designed so a bridle is not needed; when kiting a sailplane for launch, the tether meets the wing at a single point. A kite may have fixed or moving anchors. Untraditionally in technical kiting, a kite consists of tether-set-coupled wing sets; even in technical kiting, though, a wing in the system is still often called the kite.
The lift that sustains the kite in flight is generated when air flows around the kite’s surface, producing low pressure above and high pressure below the wings. The interaction with the wind also generates horizontal drag along the direction of the wind. The resultant force vector from the lift and drag force components is opposed by the tension of one or more of the lines or tethers to which the kite is attached. The anchor point of the kite line may be static or moving (such as the towing of a kite by a running person, boat, free-falling anchors as in paragliders and fugitive parakites or vehicle).
The same principles of fluid flow apply in liquids and kites are also used under water. A hybrid tethered craft comprising both a lighter-than-air balloon as well as a kite lifting surface is called a kytoon.
Kites have a long and varied history and many different types are flown individually and at festivals worldwide. Kites may be flown for recreation, art or other practical uses. Sport kites can be flown in aerial ballet, sometimes as part of a competition. Power kites are multi-line steerable kites designed to generate large forces which can be used to power activities such as kite surfing, kite landboarding, kite fishing, kite buggying and a new trend snow kiting. Even Man-lifting kites have been made.
"""
tokens=tokenizer.tokenize(kite_txt.lower())
token_counts=Counter(tokens)
print(token_counts)

上述例子里,里面有很多停用词,这篇文章不太可能会与“the”、“a”等词相关。下面把这些词去掉:

import nltk
nltk.download('stopwords',quiet=True)
stop_words=nltk.corpus.stopwords.words('english')
tokens=[x for x in tokens if x not in stop_words]
kite_counts=Counter(tokens)
print(kite_counts)

单纯凭借浏览词在文档中出现的次数,我们就可以学到一些东西。比如词项kite、wing、lift都很重要。

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值