原理介绍
fasttext是facebook开源的一个词向量与文本分类工具,在2016年开源,典型应用场景是“带监督的文本分类问题”。提供简单而高效的文本分类和表征学习的方法,性能比肩深度学习而且速度更快。
fastText的架构和word2vec中的CBOW的架构类似,因为它们的作者都是Facebook的科学家Tomas Mikolov,而且确实fastText也算是words2vec所衍生出来的。
具体原理不细讲了,可以参考后面的链接。(建议直接翻到最后看后续,有彩蛋)
安装
重点说问题,上代码。
fasttext适用于linux环境下,pip install fasttext生成的model.bin文件在调用时,结果会是nan
1. 下载source code(zip)文件:https://github.com/xiamx/fastText/releases
2. 到下载的路径下,pip install XXXX.zip
------------------
另外有发现一种解决办法: `但是这种方法导致我原来的模型加载不了了。。。。`
git clone https://github.com/facebookresearch/fastText.git
cd fastText
pip install .
代码示例
训练数据和测试数据来自网盘:
https://pan.baidu.com/s/1jH7wyOY
https://pan.baidu.com/s/1slGlPgx
import fastText.FastText as ff
classifier = ff.train_supervised(r"news_fasttext_train.txt")
model = classifier.save_model(r'fasttext1.model') # 保存模型
classifier = ff.load_model(r'fasttext1.model') # 加载保存的模型
test = classifier.test(r"news_fasttext_test.txt") # 输出测试结果
classifier.get_labels() # 输出标签
pre = classifier.predict('快讯 : 美国 4 月 营建 开支 环比 增 0.4 % 好于 预期 欢迎 发表 评论 我要 评论 ') #输出改文本的预测结果
print(pre)
这里不得不说还有一个坑,训练数据和测试数据的路径不能有中文。。。不知道什么鬼,几年前也曾经遇到过这种问题,但是近来没发现中文报啥错,可能是sklearn TensorFlow什么的有专门的处理,总之,这里中文路径很痛苦。。
参考链接:
https://blog.youkuaiyun.com/john_bh/article/details/79268850
https://blog.youkuaiyun.com/grafx/article/details/78697881
https://blog.youkuaiyun.com/yick_liao/article/details/62222153
https://blog.youkuaiyun.com/sinat_26917383/article/details/54850933
https://blog.youkuaiyun.com/lxg0807/article/details/52960072
------------------------我是分割线----------------------------------
后续
然鹅经历了几个月之后,重新安装按上面操作遇到了问题,于是有发现了新的安装方法
Pip install fasttext-0.8.3-cp36-cp36m-win_amd64.whl
https://www.lfd.uci.edu/~gohlke/pythonlibs/#fasttext
fastText实现方法
import fastText.FastText as ff
from gensim.models import FastText
https://www.cnblogs.com/gaofighting/p/9552821.html
-------------------------------
Linux 安装方法(参考:https://blog.youkuaiyun.com/weixin_44177568/article/details/102511480) 亲测可行~
git clone https://github.com/facebookresearch/fastText.git
cd fastText
pip install .
简单说下这个fasttext包安装的坑, 有的python版本是没有对应包的,更没有wheel文件, 只能下载源码,去pip install、
其它相关链接:
https://blog.youkuaiyun.com/weixin_44388679/article/details/88937700
https://blog.youkuaiyun.com/qq_17814041/article/details/80041189