MENU

fastText 细节及实践

June 16, 2020 • Read: 6700 • Deep Learning阅读设置

fastText 模型是类似 CBOW 的三层结构,关于这个结构的介绍,很多博客都讲了,这里我不多赘述,我主要叙述一下其中的部分细节

N-gram

输入层是文档中所有词的词向量和文档中各个单词的 n-gram 向量。隐藏层是这些向量的叠加平均

从输入开始,fastText 和 CBOW 就不一样,主要在于 fastText 的输入还包括每个单词的 n-gram。举个例子,假设某个文档中只有三个词 I like apple,N-gram 的 N 取 3,那么隐藏层可表示为

这样做有什么好处?我们知道,"apple" 和 "apples" 在通常情况下几乎是同一个意思,但是如果仅使用传统的方法,以词为单位作为输入,输入的是每个词的 one-hot 编码,而 "apple" 和 "apples" 的 one-hot 可能并没有任何关系。但如果考虑 n-gram,它俩在字符级别是非常相似的,这样最终训练出来的词向量相比传统方法会更好

Hash

由于 n-gram 的量远比 word 大的多,完全存下所有的 n-gram 不太现实。fastText 采用的是 Hash 桶的方式,把所有的 n-gram 映射到 buckets 个桶中,而映射到相同桶的 n-gram 共享同一个 embedding vector,如下图所示

图中 Win 代表整个 Embedding 矩阵,其中前 V 行是 word Embedding,后 Buckets 行是 n-gram Embedding,每个 n-gram 通过 hash 函数之后映射到 0~Bucket-1 位置,得到对应的 embedding 向量。用哈希的方式既能保证查找时 O (1) 的效率,又可能把内存消耗控制在 O (buckets * dim) 范围内。不过这种方法潜在的问题是存在哈希冲突,不同的 n-gram 可能会共享同一个 embedding。如果桶大小取的足够大,这种影响会很小

实践

实验的平台为 google colab

首先安装 fastText,可能您看到这篇文章的时候,fastText 已经更新了最新版本,在这里查看最新的版本号

  • !wget https://github.com/facebookresearch/fastText/archive/v0.9.2.zip
  • !unzip v0.9.2.zip
  • %cd fastText-0.9.2
  • !make

自定义一个简单的数据集,做文本分类任务,其中__label__是每个类别的默认前缀

  • # 0 is positive, 1 is negative
  • with open('train.txt', 'w') as f:
  • f.write('__label__0 i love you\n')
  • f.write('__label__0 he loves me\n')
  • f.write('__label__0 she likes baseball\n')
  • f.write('__label__1 i hate you\n')
  • f.write('__label__1 sorry for that\n')
  • f.write('__label__1 this is awful')
  • with open('test.txt', 'w') as f:
  • f.write('i like you\n')
  • f.write('sorry hate you\n')

然后开始训练,后面所跟的详细参数说明,可以看这篇文章

  • !./fasttext supervised -input train.txt -output model -dim 2 -wordNgrams 2 -lr 0.7 -epoch 50 -loss ns -neg 2

最后对测试集进行预测

  • !cat test.txt
  • !./fasttext predict model.bin test.txt

如果想了解 python 代码调用 fastText 的方式,可以查看我的这篇文章

参考文献

N-gram 特征,浅谈 FastText 文本分类利器解读 (2)

Last Modified: April 29, 2021
Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment

4 Comments
  1. Aiden Aiden

    学长我好崇拜你,目前正在 21 考研备考,向您看齐!!!

    1. mathor mathor

      @Aiden 加油

  2. 看了你好多博客的粉丝 看了你好多博客的粉丝

    python 代码调用 fastText 的文章的密码是什么呀

  3. maggie maggie

    请教两个个问题:

    比如三个词 {a bcd ef},比如我取 n-grams=2,那么对于中英文来说:
    A: a bcd ef + 「a/bcd ,bcd/ef」

    B: a bcd ef + 「bc,cd」
    这里是对 A 还是 B 取平均呢?

    A: 小米手机 很好用 + 「小米手机 / 很好用」
    B: 小米手机 很好用 + 「小米,米手,手机,很好,好用」
    同样,这里是对 A 还是 B 取平均呢?

    wordNgrams 和 minn/maxn 之间是什么关系呢?

    希望您解答,谢谢!(* ̄︶ ̄)