Mallet是Umass大牛开发的一个关于统计自然语言处理的l的开源库,很好的一个东西。可以用来学topic model,训练ME模型等。对于开发者来说,其官网的技术文档是非常有效的。

mallet下载地址,浏览开发者文档,只需点击相应的“Developer's Guide”。

下面以开发一个简单的最大熵分类模型为例,可参考文档

首先下载mallet工具包,该工具包中包含代码和jar包,简单起见,我们导入mallet-2.0.7\dist下的mallet.jar和mallet-deps.jar,导入jar包过程为:项目右击->Properties->Java Build Path->Libraries,点击“Add JARs”,在路径中选取相应的jar包即可。

新建Maxent类,代码如下:

  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileOutputStream;
  5. import java.io.FileReader;
  6. import java.io.IOException;
  7. import java.io.ObjectInputStream;
  8. import java.io.ObjectOutputStream;
  9. import java.io.Serializable;
  10. import java.util.ArrayList;
  11. import java.util.Arrays;
  12. import java.util.List;
  13.  
  14. import cc.mallet.classify.Classifier;
  15. import cc.mallet.classify.ClassifierTrainer;
  16. import cc.mallet.classify.MaxEntTrainer;
  17. import cc.mallet.classify.Trial;
  18. import cc.mallet.pipe.iterator.CsvIterator;
  19. import cc.mallet.types.Alphabet;
  20. import cc.mallet.types.FeatureVector;
  21. import cc.mallet.types.Instance;
  22. import cc.mallet.types.InstanceList;
  23. import cc.mallet.types.Label;
  24. import cc.mallet.types.LabelAlphabet;
  25. import cc.mallet.types.Labeling;
  26. import cc.mallet.util.Randoms;
  27.  
  28. public class Maxent implements Serializable{
  29.  
  30. //Train a classifier
  31. public static Classifier trainClassifier(InstanceList trainingInstances) {
  32. // Here we use a maximum entropy (ie polytomous logistic regression) classifier.
  33. ClassifierTrainer trainer = new MaxEntTrainer();
  34. return trainer.train(trainingInstances);
  35. }
  36.  
  37. //save a trained classifier/write a trained classifier to disk
  38. public void saveClassifier(Classifier classifier,String savePath) throws IOException{
  39. ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(savePath));
  40. oos.writeObject(classifier);
  41. oos.flush();
  42. oos.close();
  43. }
  44.  
  45. //restore a saved classifier
  46. public Classifier loadClassifier(String savedPath) throws FileNotFoundException, IOException, ClassNotFoundException{
  47. // Here we load a serialized classifier from a file.
  48. Classifier classifier;
  49. ObjectInputStream ois = new ObjectInputStream (new FileInputStream (new File(savedPath)));
  50. classifier = (Classifier) ois.readObject();
  51. ois.close();
  52. return classifier;
  53. }
  54.  
  55. //predict & evaluate
  56. public String predict(Classifier classifier,Instance testInstance){
  57. Labeling labeling = classifier.classify(testInstance).getLabeling();
  58. Label label = labeling.getBestLabel();
  59. return (String)label.getEntry();
  60. }
  61.  
  62. public void evaluate(Classifier classifier, String testFilePath) throws IOException {
  63. InstanceList testInstances = new InstanceList(classifier.getInstancePipe());
  64.  
  65. //format of input data:[name] [label] [data ... ]
  66. CsvIterator reader = new CsvIterator(new FileReader(new File(testFilePath)),"(\\w+)\\s+(\\w+)\\s+(.*)",3, 2, 1); // (data, label, name) field indices
  67.  
  68. // Add all instances loaded by the iterator to our instance list
  69. testInstances.addThruPipe(reader);
  70. Trial trial = new Trial(classifier, testInstances);
  71.  
  72. //evaluation metrics.precision, recall, and F1
  73. System.out.println("Accuracy: " + trial.getAccuracy());
  74. System.out.println("F1 for class 'good': " + trial.getF1("good"));
  75. System.out.println("Precision for class '" +
  76. classifier.getLabelAlphabet().lookupLabel(1) + "': " +
  77. trial.getPrecision(1));
  78. }
  79.  
  80. //perform n-fold cross validation
  81. public static Trial testTrainSplit(MaxEntTrainer trainer, InstanceList instances) {
  82. int TRAINING = 0;
  83. int TESTING = 1;
  84. int VALIDATION = 2;
  85.  
  86. // Split the input list into training (90%) and testing (10%) lists.
  87. InstanceList[] instanceLists = instances.split(new Randoms(), new double[] {0.9, 0.1, 0.0});
  88. Classifier classifier = trainClassifier(instanceLists[TRAINING]);
  89. return new Trial(classifier, instanceLists[TESTING]);
  90. }
  91.  
  92. public static void main(String[] args) throws FileNotFoundException,IOException{
  93. //define training samples
  94. Alphabet featureAlphabet = new Alphabet();//特征词典
  95. LabelAlphabet targetAlphabet = new LabelAlphabet();//类标词典
  96. targetAlphabet.lookupIndex("positive");
  97. targetAlphabet.lookupIndex("negative");
  98. targetAlphabet.lookupIndex("neutral");
  99. targetAlphabet.stopGrowth();
  100. featureAlphabet.lookupIndex("f1");
  101. featureAlphabet.lookupIndex("f2");
  102. featureAlphabet.lookupIndex("f3");
  103. InstanceList trainingInstances = new InstanceList (featureAlphabet,targetAlphabet);//实例集对象
  104. final int size = targetAlphabet.size();
  105. double[] featureValues1 = {1.0, 0.0, 0.0};
  106. double[] featureValues2 = {2.0, 0.0, 0.0};
  107. double[] featureValues3 = {0.0, 1.0, 0.0};
  108. double[] featureValues4 = {0.0, 0.0, 1.0};
  109. double[] featureValues5 = {0.0, 0.0, 3.0};
  110. String[] targetValue = {"positive","positive","neutral","negative","negative"};
  111. List<double[]> featureValues = Arrays.asList(featureValues1,featureValues2,featureValues3,featureValues4,featureValues5);
  112. int i = 0;
  113. for(double[]featureValue:featureValues){
  114. FeatureVector featureVector = new FeatureVector(featureAlphabet,
  115. (String[])targetAlphabet.toArray(new String[size]),featureValue);//change list to array
  116. Instance instance = new Instance (featureVector,targetAlphabet.lookupLabel(targetValue[i]), "xxx",null);
  117. i++;
  118. trainingInstances.add(instance);
  119. }
  120.  
  121. Maxent maxent = new Maxent();
  122. Classifier maxentclassifier = maxent.trainClassifier(trainingInstances);
  123. //loading test examples
  124. double[] testfeatureValues = {0.5, 0.5, 6.0};
  125. FeatureVector testfeatureVector = new FeatureVector(featureAlphabet,
  126. (String[])targetAlphabet.toArray(new String[size]),testfeatureValues);
  127. //new instance(data,target,name,source)
  128. Instance testinstance = new Instance (testfeatureVector,targetAlphabet.lookupLabel("negative"), "xxx",null);
  129. System.out.print(maxent.predict(maxentclassifier, testinstance));
  130. //maxent.evaluate(maxentclassifier, "resource/testdata.txt");
  131. }
  132. }

说明:trainingInstances为训练样本,testinstance为测试样本,该程序的执行结果为“negative”。

Eclipse下mallet使用的方法的更多相关文章

  1. eclipse下maven一些配置方法汇总

    随着eclipse的不同版本的变更:对maven插件的安装也有着不同的差异:之前也在一些版本的eclipse上安装成功地,但是最近又遇到了一些麻烦,故将这些方法记录下来: 大家都知道的最常用的一种方式 ...

  2. eclipse下使用cygwin的方法(Windows下用eclipse玩gcc/g++和gdb)

    明天就回国了,今晚回国前写写如何配置eclipse和CDT.这个配置方法网上讨论不是很多,可能用的人少,毕竟Windows上写C++程序多数喜欢VS,即使写的是Linux程序,很多人仍然会用VS(说只 ...

  3. Eclipse 下安装 SVN的方法

    http://welcome66.iteye.com/blog/1845176 eclipse里安装SVN插件,一般来说,有两种方式: 直接下载SVN插件,将其解压到eclipse的对应目录里 使用e ...

  4. eclipse下修改项目名导致tomcat内发布名不一致的解决方法 .

    eclipse下修改项目名导致tomcat内发布名不一致的解决方法 . ------------------------------------------------------- 解决方案: 直接 ...

  5. eclipse下java中凝视字体太小和xml中中文字体太小问题解决方法

    我们在win7下进行android应用开发.须要搭建对应的开发环境.如今普遍基本上都是eclipse+adt+sdk,在本人搭建完环境后,发现eclipse下.java中的凝视和xml中的中文字体变得 ...

  6. eclipse下Android工程名称的修改方法

    eclipse下Android工程名称的修改方法 对于已经建立的工程,如果发现原来的工程名不合适,此时若想彻底更改工程名,需要三个步骤: 1.更改工程名 选中工程名,右键-->Refactor- ...

  7. Eclipse下配置javaweb项目快速部署到tomcat

    用惯了VS,再用Eclipse,完全有一种从自动挡到手动挡的感觉啊. 很多同学在Eclipse下开发web项目,每一次修改代码,看效果的时候都有右键项目->Run as -> Run on ...

  8. eclipse maven update error 解决方法

    eclipse  maven  update error 解决方法     本来真不想写这篇博文的,但是eclipse和maven真的是太操蛋了,动不动就出了一些乱七八糟的问题,记录一下.希望公司能早 ...

  9. eclipse下maven项目保持原有目录结构配置resin运行环境

    maven项目用起来很方便,但是它的目录结构和eclipse的目录结构是有区别的,故而在eclipse下的maven项目,直接运行调试是有一些问题的. 为了方便maven项目的运行调试,因而也就有了像 ...

随机推荐

  1. NYOJ 208 Supermarket (模拟+并查集)

    题目链接 描述 A supermarket has a set Prod of products on sale. It earns a profit px for each product x∈Pr ...

  2. ueditor和thinkphp框架整合修改版

    基于tp官网上的一篇文章修改的  因为tp中所有目录其实都是性对于入口文件的 在原来的基础上略做修改后 已经做到 无论项目放在www下的任何位置 图片在编辑器中回填后都能正常显示! http://fi ...

  3. python简单爬虫(二)

    上一篇简单的实现了获取url返回的内容,在这一篇就要第返回的内容进行提取,并将结果保存到html中. 一 . 需求: 抓取主页面:百度百科Python词条   https://baike.baidu. ...

  4. 数据库管理软件 Navicat Premium12 破解步骤

    数据库管理软件  Navicat Premium12B    https://pan.baidu.com/s/1QnAQwW-q0SQ1JglpFGxKOA   密码 : mwqc 里面的软件和补丁是 ...

  5. 笔记本自开wifi设置

    笔记本自开wifi设置 是这样的有些笔记本他自身就可以放出热点供其他的小伙伴们连接,不用非得去下专门的工具有些笔记本的网卡是自带支持双收发的(这里注意我指的是有些笔记本不是全部) 命令我已经写出来了  ...

  6. 函数参数 f_arg, *args, **kwargs

    当需要给函数传参时,可以通过运用不同的形参来传递,达到参数不同的使用目的. 简单来说:f_arg就是传递的第一个参数,类似于C++中的普通参数: *args 传递的是一个参数的list: **kwar ...

  7. 理解一条语句:SELECT difference(sum("value")) FROM "mq_enqueue" WHERE "channel" =~ /ActiveMQ_TEST/ AND $timeFilter GROUP BY time($interval)

    最近使用grafana在查询InfluxDB中,用到了这一条语句 SELECT difference(sum("value")) FROM "mq_enqueue&quo ...

  8. C#子线程中更新ui-----c# 多线程多文件批量下载

    c# 多线程多文件批量下载   废话少说,先演示一张效果图 简单说下过程喽 开发过程中其实总是会碰到项目想应用下载文件~ 看其他语言有很多封装好的类库可以使用~~ 作为小白的我并没有找到很多c#的案例 ...

  9. LeetCode解题报告—— Minimum Window Substring && Largest Rectangle in Histogram

    1. Minimum Window Substring Given a string S and a string T, find the minimum window in S which will ...

  10. EF – 5.DbSet与DbContext,数据更新奥秘

    5.6.4 <DbSet与DbContext> 介绍DbSet与DbContext中的核心属性及重要方法. 5.6.5 <数据更新的奥秘>  这一讲极为重要,因为它揭示出了En ...