fasttext的基本使用 java 、python为例子
今天早上在地铁上看到知乎上看到有人使用fasttext进行文本分类,到公司试了下情况在GitHub上找了下,最开始是c++版本的实现,不过有Java、Python版本的实现了,正好拿下来试试手,
python情况:
python版本参考,作者提供了详细的实现,并且提供了中文分词之后的数据,正好拿下来用用,感谢作者,代码提供的数据作者都提供了,点后链接在上面有百度盘,可下载,java接口用到的数据也一样:
- http://blog.csdn.net/lxg0807/article/details/52960072
- import logging
- import fasttext
- logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
- #classifier = fasttext.supervised("fasttext/news_fasttext_train.txt","fasttext/news_fasttext.model",label_prefix="__label__")
- #load训练好的模型
- classifier = fasttext.load_model('fasttext/news_fasttext.model.bin', label_prefix='__label__')
- result = classifier.test("fasttext/news_fasttext_test.txt")
- print(result.precision)
- print(result.recall)
- labels_right = []
- texts = []
- with open("fasttext/news_fasttext_test.txt") as fr:
- lines = fr.readlines()
- for line in lines:
- labels_right.append(line.split(" ")[1].rstrip().replace("__label__",""))
- texts.append(line.split(" ")[0])
- # print labels
- # print texts
- # break
- labels_predict = [e[0] for e in classifier.predict(texts)] #预测输出结果为二维形式
- # print labels_predict
- text_labels = list(set(labels_right))
- text_predict_labels = list(set(labels_predict))
- print(text_predict_labels)
- print(text_labels)
- A = dict.fromkeys(text_labels,0) #预测正确的各个类的数目
- B = dict.fromkeys(text_labels,0) #测试数据集中各个类的数目
- C = dict.fromkeys(text_predict_labels,0) #预测结果中各个类的数目
- for i in range(0,len(labels_right)):
- B[labels_right[i]] += 1
- C[labels_predict[i]] += 1
- if labels_right[i] == labels_predict[i]:
- A[labels_right[i]] += 1
- print(A )
- print(B)
- print( C)
- #计算准确率,召回率,F值
- for key in B:
- p = float(A[key]) / float(B[key])
- r = float(A[key]) / float(C[key])
- f = p * r * 2 / (p + r)
- print ("%s: p:%f %fr: %f" % (key,p,r,f))
java版本情况:
githup上下载地址:
- https://github.com/ivanhk/fastText_java
看了下sh脚本的使用方法,自己简单些了个text的方法,正好用用,后面会拿xgboost进行对比,看看效果,效果可以的写成service进行上线:
- package test;
- import java.util.List;
- import fasttext.FastText;
- import fasttext.Main;
- import fasttext.Pair;
- public class Test {
- public static void main(String[] args) throws Exception {
- String[] text = {
- "supervised",
- "-input",
- "/Users/shuubiasahi/Documents/python/fasttext/news_fasttext_train.txt",
- "-output", "/Users/shuubiasahi/Documents/faste.model", "-dim",
- "10", "-lr", "0.1", "-wordNgrams", "2", "-minCount", "1",
- "-bucket", "10000000", "-epoch", "5", "-thread", "4" };
- Main op = new Main();
- op.train(text);
- FastText fasttext = new FastText();
- String[] test = { "就读", "科技", "学生" ,"学生","学生"};
- fasttext.loadModel("/Users/shuubiasahi/Documents/faste.model.bin");
- List<Pair<Float, String>> list = fasttext.predict(test, 6); //得到最大可能的六个预测概率
- for (Pair<Float, String> parir : list) {
- System.out.println("key is:" + parir.getKey() + " value is:"
- + parir.getValue());
- }
- System.out.println(Math.exp(list.get(0).getKey())); //得到最大预测概率
- }
- }
这里设置bucket不适用设置过大,过大会产生OOM,而且模型保存太大,上面的设置模型保存就有1个g,-wordNgrams可以设置为2比设置为1能提高模型分类的准确性,
结果情况:
key is:0.0 value is:__label__edu
key is:-17.75125 value is:__label__affairs
key is:-17.75125 value is:__label__economic
key is:-17.75125 value is:__label__ent
key is:-17.75125 value is:__label__fashion
key is:-17.75125 value is:__label__game
1.0
注意fasttext对输入格式有要求,label标签使用 “__label__”+实际标签的形式, over
有问题联系我
2016年5月26 我的模型已经上线了 效果还不错