fasttext安装使用

环境要求:

  • python版本2.7或≥3.4
  • Mac OS和Linux(需要具有良好C ++ 11支持的编译器)

1、当前环境:

Mac Os 
python3.7.2

2、获取fasttext最新开发版本

git clone https://github.com/facebookresearch/fastText.git

3、安装

cd fastText 

//使用python setup.py安装 
python setup.py install 

//或者使用pip安装(注:python3之后的pip都为pip3) 
pip3 install .


ps:安装过程中会给python装一个【numpy】库

一个运行速度非常快的数学库,主要用于数组计算,包含:

  • 一个强大的N维数组对象 ndarray
  • 广播功能函数
  • 整合 C/C++/Fortran 代码的工具
  • 线性代数、傅里叶变换、随机数生成等功能

4、获取训练数据

wget https://dl.fbaipublicfiles.com/fasttext/data/cooking.stackexchange.tar.gz 

//将数据集解压到某个文件夹下 
tar xzvf cooking.stackexchange.tar.gz -c ./data

5、简单使用fasttext

//进入python3命令行 
dreamdeMacBook-Pro:fastText user$ python3 
Python 3.7.2 (v3.7.2:9a3ffc0492, Dec 24 2018, 02:44:43) 
[Clang 6.0 (clang-600.0.57)] on darwin 
Type "help", "copyright", "credits" or "license" for more information.

//导入fasttext模块 
>>> import fasttext

//以cooking.stackexchange.txt为训练集训练模型model 
>>> model = fasttext.train_supervised('./data/cooking.stackexchange.txt') 
Read 0M words 
Number of words: 16568 
Number of labels: 736 
Progress: 100.0% words/sec/thread: 86310 lr: 0.000000 avg.loss: 9.870326 ETA: 0h 0m 0s

6、预测某串字符串的标签

//默认返回1个概率最高的标签 
>>> print(model.predict("Cook a frozen cobbler in a microwave instead of oven")) 
(('__label__baking',), array([0.0728373])) 

//k=3表示,返回3个预测标签 
>>> print(model.predict("Cook a frozen cobbler in a microwave instead of oven", k=3)) 
(('__label__baking', '__label__equipment', '__label__substitutions'), array([0.0728373 , 0.03996802, 0.03626037])) 

//可以同时预测多个字符串 
>>> print(model.predict(["Cook a frozen cobbler in a microwave instead of oven", "Michelin Three Star Restaurant"])) 
([['__label__baking'], ['__label__food-safety']], [array([0.0728373], dtype=float32), array([0.02446871], dtype=float32)])

7、预测某字符的精准率Precision和召回率Recall

//将原数据集后3000个分离出,作为测试集 
tail -n 3000 cooking.stackexchange.txt > cooking.valid

然后在【5】的基础上:

//1、定义print_result函数 
>>> def print_results(N, p, r): 
... print("N\t" + str(N)) 
... print("P@{}\t{:.3f}".format(1, p)) 
... print("R@{}\t{:.3f}".format(1, r)) 

//2、调用test函数进行预测 
>>> print_results(*model.test("./data/cooking.valid")) 
N 3000 
P@1 0.172 
R@1 0.075

预测结果名词解释:

含义:预测的多个结果标签中正确标签的概率
示例:如第6步中k=3时的预测结果有3个标签,其中只有一个标签是正确的,那 精准率 = 1/3 = 0.33

含义:被检测字符串的真实标签中被预测正确的标签个数占比

示例:如第6步中k=3时的预测结果中只有一个标签是正确的,而被检测的字符串实际上有5个标签,那 召回率 = 1/5 = 0.2

 

参考文档:https://pypi.org/project/fasttext/

                  https://blog.csdn.net/feilong_csdn/article/details/88655927

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值