fasttext的基本使用 java 、python为例子

fasttext的基本使用 java 、python为例子

今天早上在地铁上看到知乎上看到有人使用fasttext进行文本分类,到公司试了下情况在GitHub上找了下,最开始是c++版本的实现,不过有JavaPython版本的实现了,正好拿下来试试手,

python情况:

python版本参考,作者提供了详细的实现,并且提供了中文分词之后的数据,正好拿下来用用,感谢作者,代码提供的数据作者都提供了,点后链接在上面有百度盘,可下载,java接口用到的数据也一样:

[html] view plain copy

  1. http://blog.csdn.net/lxg0807/article/details/52960072

[python] view plain copy

  1. import logging
  2. import fasttext
  3. logging.basicConfig(format=‘%(asctime)s : %(levelname)s : %(message)s‘, level=logging.INFO)
  4. #classifier = fasttext.supervised("fasttext/news_fasttext_train.txt","fasttext/news_fasttext.model",label_prefix="__label__")
  5. #load训练好的模型
  6. classifier = fasttext.load_model(‘fasttext/news_fasttext.model.bin‘, label_prefix=‘__label__‘)
  7. result = classifier.test("fasttext/news_fasttext_test.txt")
  8. print(result.precision)
  9. print(result.recall)
  10. labels_right = []
  11. texts = []
  12. with open("fasttext/news_fasttext_test.txt") as fr:
  13. lines = fr.readlines()
  14. for line in lines:
  15. labels_right.append(line.split("\t")[1].rstrip().replace("__label__",""))
  16. texts.append(line.split("\t")[0])
  17. #     print labels
  18. #     print texts
  19. #     break
  20. labels_predict = [e[0] for e in classifier.predict(texts)] #预测输出结果为二维形式
  21. # print labels_predict
  22. text_labels = list(set(labels_right))
  23. text_predict_labels = list(set(labels_predict))
  24. print(text_predict_labels)
  25. print(text_labels)
  26. A = dict.fromkeys(text_labels,0)  #预测正确的各个类的数目
  27. B = dict.fromkeys(text_labels,0)   #测试数据集中各个类的数目
  28. C = dict.fromkeys(text_predict_labels,0) #预测结果中各个类的数目
  29. for i in range(0,len(labels_right)):
  30. B[labels_right[i]] += 1
  31. C[labels_predict[i]] += 1
  32. if labels_right[i] == labels_predict[i]:
  33. A[labels_right[i]] += 1
  34. print(A )
  35. print(B)
  36. print( C)
  37. #计算准确率,召回率,F值
  38. for key in B:
  39. p = float(A[key]) / float(B[key])
  40. r = float(A[key]) / float(C[key])
  41. f = p * r * 2 / (p + r)
  42. print ("%s:\tp:%f\t%fr:\t%f" % (key,p,r,f))

java版本情况:

githup上下载地址:

[html] view plain copy

  1. https://github.com/ivanhk/fastText_java

看了下sh脚本的使用方法,自己简单些了个text的方法,正好用用,后面会拿xgboost进行对比,看看效果,效果可以的写成service进行上线:

[java] view plain copy

  1. package test;
  2. import java.util.List;
  3. import fasttext.FastText;
  4. import fasttext.Main;
  5. import fasttext.Pair;
  6. public class Test {
  7. public static void main(String[] args) throws Exception {
  8. String[] text = {
  9. "supervised",
  10. "-input",
  11. "/Users/shuubiasahi/Documents/python/fasttext/news_fasttext_train.txt",
  12. "-output", "/Users/shuubiasahi/Documents/faste.model", "-dim",
  13. "10", "-lr", "0.1", "-wordNgrams", "2", "-minCount", "1",
  14. "-bucket", "10000000", "-epoch", "5", "-thread", "4" };
  15. Main op = new Main();
  16. op.train(text);
  17. FastText fasttext = new FastText();
  18. String[] test = { "就读", "科技", "学生" ,"学生","学生"};
  19. fasttext.loadModel("/Users/shuubiasahi/Documents/faste.model.bin");
  20. List<Pair<Float, String>> list = fasttext.predict(test, 6);  //得到最大可能的六个预测概率
  21. for (Pair<Float, String> parir : list) {
  22. System.out.println("key is:" + parir.getKey() + "   value is:"
  23. + parir.getValue());
  24. }
  25. System.out.println(Math.exp(list.get(0).getKey()));  //得到最大预测概率
  26. }
  27. }

这里设置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   我的模型已经上线了    效果还不错

时间: 2025-01-07 16:14:41

fasttext的基本使用 java 、python为例子的相关文章

梯度迭代树(GBDT)算法原理及Spark MLlib调用实例(Scala/Java/python)

梯度迭代树(GBDT)算法原理及Spark MLlib调用实例(Scala/Java/python) http://blog.csdn.net/liulingyuan6/article/details/53426350 梯度迭代树 算法简介: 梯度提升树是一种决策树的集成算法.它通过反复迭代训练决策树来最小化损失函数.决策树类似,梯度提升树具有可处理类别特征.易扩展到多分类问题.不需特征缩放等性质.Spark.ml通过使用现有decision tree工具来实现. 梯度提升树依次迭代训练一系列的

[LeetCode] 011. Container With Most Water (Medium) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 011.Container_With_Most_Water (Medium) 链接: 题目:https://oj.leetcode.com/problems/container-with-most-water/ 代码(github):https://github.com/illuz/leetcode 题意: 给一些

[LeetCode] 012. Integer to Roman (Medium) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 012.Integer_to_Roman (Medium) 链接: 题目:https://oj.leetcode.com/problems/integer-to-roman/ 代码(github):https://github.com/illuz/leetcode 题意: 把十进制转为罗马数. 分析: 模拟即可.

[LeetCode] 013. Roman to Integer (Easy) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 013.Roman_to_Integer (Easy) 链接: 题目:https://oj.leetcode.com/problems/roman-to-integer/ 代码(github):https://github.com/illuz/leetcode 题意: 把罗马数转为十进制. 分析: 跟 012. I

[LeetCode] 004. Median of Two Sorted Arrays (Hard) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 004.Median_of_Two_Sorted_Arrays (Hard) 链接: 题目:https://oj.leetcode.com/problems/Median-of-Two-Sorted-Arrays/ 代码(github):https://github.com/illuz/leetcode 题意: 求

[LeetCode] 005. Longest Palindromic Substring (Medium) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 005.Longest_Palindromic_Substring (Medium) 链接: 题目:https://oj.leetcode.com/problems/Longest-Palindromic-Substring/ 代码(github):https://github.com/illuz/leetcode

[LeetCode] 006. ZigZag Conversion (Easy) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 006.ZigZag_Conversion (Easy) 链接: 题目:https://oj.leetcode.com/problems/zigzag-conversion/ 代码(github):https://github.com/illuz/leetcode 题意: 把一个字符串按横写的折线排列. 分析: 直

常见的几种语言C,C#,JAVA,Python的运行原理

相对于常见的几种语言C,C#,JAVA,Python的运行原理 由于CPU只能识别机器码,即我们常说的二进制码01010101 有任何语言在计算机上运行最终都要转化成CPU能够识别的机器码010101 对于C语言:通过C语言代码编译器将C语言写出的代码进行编译得到机器码,然后机器码就可以交给CPU去识别,即运行 对于其他语言:代码编译器将代码编译成字节码,然后通过各自的虚拟机将字节码进一步处理(转换)成机器码(0101010101),然后在处理器上运行 Python和C 首先Python是用C开

[LeetCode] 020. Valid Parentheses (Easy) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 020.Valid_Parentheses (Easy) 链接: 题目:https://oj.leetcode.com/problems/valid-parentheses/ 代码(github):https://github.com/illuz/leetcode 题意: 判断一个括号字符串是否是有效的. 分析: