学习目标
学习FastText的使用和基础原理
学会使用验证集进行调参
FastText
FastText是一种典型的深度学习词向量的表示方法,它非常简单通过Embedding层将单词映射到稠密空间,然后将句子中所有的单词在Embedding空间中进行平均,进而完成分类操作。
所以FastText是一个三层的神经网络,输入层、隐含层和输出层。
Bag of Tricks for Efficient Text Classification, https://arxiv.org/abs/1607.01759
基于FastText的文本分类
FastText可以快速的在CPU上进行训练,最好的实践方法就是官方开源的版本: https://github.com/facebookresearch/fastText/tree/master/python
pip安装
pip install fasttext
源码安装
git clone https://github.com/facebookresearch/fastText.git
cd fastText
sudo pip install .
两种安装方法都可以安装,如果你是初学者可以优先考虑使用pip安装。
import pandas as pd
from sklearn.metrics import f1_score
# 转换为FastText需要的格式
train_df = pd.read_csv('../data/train_set.csv', sep='\t', nrows=15000)
train_df['label_ft'] = '__label__' + train_df['label'].astype(str)
train_df[['text','label_ft']].iloc[:-5000].to_csv('train.csv', index=None, header=None, sep='\t')
import fasttext
model = fasttext.train_supervised('train.csv', lr=1.0, wordNgrams=2,
verbose=2, minCount=1, epoch=25, loss="hs")
val_pred = [model.predict(x)[0][0].split('__')[-1] for x in train_df.iloc[-5000:]['text']]
print(f1_score(train_df['label'].values[-5000:].astype(str), val_pred, average='macro'))
# 0.82
如何使用验证集调参
在使用TF-IDF和FastText中,有一些模型的参数需要选择,这些参数会在一定程度上影响模型的精度,那么如何选择这些参数呢?
通过阅读文档,要弄清楚这些参数的大致含义,那些参数会增加模型的复杂度
通过在验证集上进行验证模型精度,找到模型在是否过拟合还是欠拟合