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类,代码如下:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import cc.mallet.classify.Classifier;
import cc.mallet.classify.ClassifierTrainer;
import cc.mallet.classify.MaxEntTrainer;
import cc.mallet.classify.Trial;
import cc.mallet.pipe.iterator.CsvIterator;
import cc.mallet.types.Alphabet;
import cc.mallet.types.FeatureVector;
import cc.mallet.types.Instance;
import cc.mallet.types.InstanceList;
import cc.mallet.types.Label;
import cc.mallet.types.LabelAlphabet;
import cc.mallet.types.Labeling;
import cc.mallet.util.Randoms; public class Maxent implements Serializable{ //Train a classifier
public static Classifier trainClassifier(InstanceList trainingInstances) {
// Here we use a maximum entropy (ie polytomous logistic regression) classifier.
ClassifierTrainer trainer = new MaxEntTrainer();
return trainer.train(trainingInstances);
} //save a trained classifier/write a trained classifier to disk
public void saveClassifier(Classifier classifier,String savePath) throws IOException{
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(savePath));
oos.writeObject(classifier);
oos.flush();
oos.close();
} //restore a saved classifier
public Classifier loadClassifier(String savedPath) throws FileNotFoundException, IOException, ClassNotFoundException{
// Here we load a serialized classifier from a file.
Classifier classifier;
ObjectInputStream ois = new ObjectInputStream (new FileInputStream (new File(savedPath)));
classifier = (Classifier) ois.readObject();
ois.close();
return classifier;
} //predict & evaluate
public String predict(Classifier classifier,Instance testInstance){
Labeling labeling = classifier.classify(testInstance).getLabeling();
Label label = labeling.getBestLabel();
return (String)label.getEntry();
} public void evaluate(Classifier classifier, String testFilePath) throws IOException {
InstanceList testInstances = new InstanceList(classifier.getInstancePipe()); //format of input data:[name] [label] [data ... ]
CsvIterator reader = new CsvIterator(new FileReader(new File(testFilePath)),"(\\w+)\\s+(\\w+)\\s+(.*)",3, 2, 1); // (data, label, name) field indices // Add all instances loaded by the iterator to our instance list
testInstances.addThruPipe(reader);
Trial trial = new Trial(classifier, testInstances); //evaluation metrics.precision, recall, and F1
System.out.println("Accuracy: " + trial.getAccuracy());
System.out.println("F1 for class 'good': " + trial.getF1("good"));
System.out.println("Precision for class '" +
classifier.getLabelAlphabet().lookupLabel(1) + "': " +
trial.getPrecision(1));
} //perform n-fold cross validation
public static Trial testTrainSplit(MaxEntTrainer trainer, InstanceList instances) {
int TRAINING = 0;
int TESTING = 1;
int VALIDATION = 2; // Split the input list into training (90%) and testing (10%) lists.
InstanceList[] instanceLists = instances.split(new Randoms(), new double[] {0.9, 0.1, 0.0});
Classifier classifier = trainClassifier(instanceLists[TRAINING]);
return new Trial(classifier, instanceLists[TESTING]);
} public static void main(String[] args) throws FileNotFoundException,IOException{
//define training samples
Alphabet featureAlphabet = new Alphabet();//特征词典
LabelAlphabet targetAlphabet = new LabelAlphabet();//类标词典
targetAlphabet.lookupIndex("positive");
targetAlphabet.lookupIndex("negative");
targetAlphabet.lookupIndex("neutral");
targetAlphabet.stopGrowth();
featureAlphabet.lookupIndex("f1");
featureAlphabet.lookupIndex("f2");
featureAlphabet.lookupIndex("f3");
InstanceList trainingInstances = new InstanceList (featureAlphabet,targetAlphabet);//实例集对象
final int size = targetAlphabet.size();
double[] featureValues1 = {1.0, 0.0, 0.0};
double[] featureValues2 = {2.0, 0.0, 0.0};
double[] featureValues3 = {0.0, 1.0, 0.0};
double[] featureValues4 = {0.0, 0.0, 1.0};
double[] featureValues5 = {0.0, 0.0, 3.0};
String[] targetValue = {"positive","positive","neutral","negative","negative"};
List<double[]> featureValues = Arrays.asList(featureValues1,featureValues2,featureValues3,featureValues4,featureValues5);
int i = 0;
for(double[]featureValue:featureValues){
FeatureVector featureVector = new FeatureVector(featureAlphabet,
(String[])targetAlphabet.toArray(new String[size]),featureValue);//change list to array
Instance instance = new Instance (featureVector,targetAlphabet.lookupLabel(targetValue[i]), "xxx",null);
i++;
trainingInstances.add(instance);
} Maxent maxent = new Maxent();
Classifier maxentclassifier = maxent.trainClassifier(trainingInstances);
//loading test examples
double[] testfeatureValues = {0.5, 0.5, 6.0};
FeatureVector testfeatureVector = new FeatureVector(featureAlphabet,
(String[])targetAlphabet.toArray(new String[size]),testfeatureValues);
//new instance(data,target,name,source)
Instance testinstance = new Instance (testfeatureVector,targetAlphabet.lookupLabel("negative"), "xxx",null);
System.out.print(maxent.predict(maxentclassifier, testinstance));
//maxent.evaluate(maxentclassifier, "resource/testdata.txt");
}
}

说明: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. 【leetcode 简单】第九题 移除元素

    给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度. 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成 ...

  2. js常见易错点

    原文:http://www.jianshu.com/p/1c77853d4f01 前言 本文是我学习JavaScript过程中收集与整理的一些易错知识点,将分别从变量作用域,类型比较,this指向,函 ...

  3. bzoj 2303 并查集

    首先如果没有限制的话,我们可以直接求出答案,假设对于n*m的矩阵,我们最上方一行和左方的一列随意确定,那么首先这写确定的状态肯定是不会不合法的,因为我们可以调整剩下的01状态来使得这一行一列的状态合法 ...

  4. redhat5.5 x64 安装oracle 11g

    http://www.cnblogs.com/jamesf/p/4769086.html http://blog.csdn.net/yakson/article/details/9012129

  5. 大美西安writeup

    http://202.112.51.184:10080/ admin/admin 弱口令登入 发现注入 但是这个注入实在是不知道怎么利用.很蛋疼.后来get了一个姿势. 先-1让前面的不被下载然后后面 ...

  6. 多个id或class属性相同的元素绑定事件

    <td class="tools"><a href="javascript:void(0);" status="0" na ...

  7. openjudge-NOI 2.6-1768 最大子矩阵

    题目链接:http://noi.openjudge.cn/ch0206/1768/ 题解: 如果用O(n4)的算法肯定会炸,需要压缩掉一维的空间,只需要简单加和就好啦 例如,我们要对样例中第2-4行D ...

  8. scrollreveal(页面滚动显示动画插件支持手机)

    scrollreveal.js是一款可以轻易实现桌面和移动浏览器元素随页面滚动产生动画的js插件.该插件通过配置可以在页面滚动,元素进入视口时产生炫酷的动画效果,同时还支持元素的3D效果,非常的实用. ...

  9. leetcode 168. Excel Sheet Column Title 171 Excel Sheet Column Number

    题目 //像10进制一样进行 转换   只是要从0开始记录 class Solution { public: string convertToTitle(int n) { char a; string ...

  10. Linux Supervisor的安装与使用入门---Ubuntun

    Linux Supervisor的安装与使用入门 在linux或者unix操作系统中,守护进程(Daemon)是一种运行在后台的特殊进程,它独立于控制终端并且周期性的执行某种任务或等待处理某些发生的事 ...