1. 安装fastText
首先需要安装numpy、scipy和pybind11。
numpy我是在安装PyTorch的时候,顺带着安装的。我使用的命令行是conda install pytorch torchvision torchaudio cudatoolkit=10.2 -c pytorch
。单独安装numpy可以参考使用conda install numpy
。 安装SciPy:conda install scipy
或 pip install scipy
安装pybind11,参考官方文档:Installing the library — pybind11 documentation:conda install -c conda-forge pybind11
或 pip install pybind11
安装完前置包之后,安装fastText:pip install fasttext
2. 训练和调用词向量模型
以前我用gensim做过。以后可以比较一下两个包的不同之处。 此外fasttext词向量论文中用的baseline是谷歌官方的word2vec包:Google Code Archive - Long-term storage for Google Code Project Hosting.
2.1 代码实现
官方详细教程:Word representations · fastText(使用的是英文维基百科的语料,本文的实验用的是中文语料)
由于fasttext本身没有中文分词功能,因此需要手动对文本预先分词。处理数据的代码可参考:
import csv,jieba
with open('data/cls/ChnSentiCorp_htl_all.csv') as f:
reader=csv.reader(f)
header = next(reader) #表头
data = [[int(row[0]),row[1]] for row in reader] #每个元素是一个由字符串组成的列表,第一个元素是标签(01),第二个元素是评论文本。
tofiledir='data/cls'
with open(tofiledir+'/corpus.txt','w') as f:
f.writelines([' '.join(jieba.cut(row[1]))+'\n' for row in data])
文件效果:
学习词向量并展示的代码:
import fasttext
model=fasttext.train_unsupervised('data/cls/corpus.txt',model='skipgram') #model入参可以更换为`cbow`
print(model.words[:10]) #打印前10个单词
print(model[model.words[9]]) #打印第10个单词的词向量
(展示词向量也可以使用get_word_vector(word)
,而且可以查找数据中未出现的data(事实上词向量是用子字符串总和来表示的))
输出:
Read 0M words
Number of words: 6736
Number of labels: 0
Progress: 100.0% words/sec/thread: 71833 lr: 0.000000 avg.loss: 2.396854 ETA: 0h 0m 0s
[',', '的', '。', ',', '了', '酒店', '是', '</s>', '很', '房间']
[ 1.44523270e-02 -1.14391923e-01 -1.31457284e-01 -1.59686044e-01
-4.57017310e-02 2.04045177e-01 2.00106978e-01 1.63031772e-01
1.71287894e-01 -2.93396801e-01 -1.01871997e-01 2.42363811e-01
2.78942972e-01 -4.99058776e-02 -1.27043173e-01 2.87460908e-02
3.73771787e-01 -1.69842303e-01 2.42533281e-01 -1.82482198e-01
7.33817369e-02 2.21920848e-01 2.17794716e-01 1.68730497e-01
2.16873884e-02 -3.15452456e-01 8.21631625e-02 -6.56387508e-02
9.51113254e-02 1.69942483e-01 1.13980576e-01 1.15132451e-01
3.28856230e-01 -4.43856061e-01 -5.13903908e-02 -1.74580872e-01
4.39242758e-02 -2.22267807e-01 -1.09185934e-01 -1.62346154e-01
2.11286068e-01 2.44934723e-01 -1.95910111e-02 2.33887792e-01
-7.72107393e-02 -6.28366888e-01 -1.30844399e-01 1.01614185e-01
-2.42928267e-02 4.28218693e-02 -3.78409088e-01 2.31552869e-01
3.49486321e-02 8.70033056e-02 -4.75800633e-01 5.37340902e-02
2.29140893e-02 3.87787819e-04 -5.77102527e-02 1.44286081e-03
1.33415654e-01 2.14263964e-02 9.26891491e-02 -2.24226922e-01
7.32692927e-02 -1.52607411e-01 -1.42978013e-01 -4.28122580e-02
9.64387357e-02 7.77726322e-02 -4.48957413e