Eclipse下mallet使用的方法

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”。

时间: 2024-08-02 20:45:19

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

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

明天就回国了,今晚回国前写写如何配置eclipse和CDT.这个配置方法网上讨论不是很多,可能用的人少,毕竟Windows上写C++程序多数喜欢VS,即使写的是Linux程序,很多人仍然会用VS(说只喜欢用VI的人我佩服).的确VS很强大,但我也geek一回,使用eclipse做C++程序(用VI才是真正的geek?好吧,我就这水准了,反正我会用VI,但不习惯VI).希望这篇小小的文章能帮助想在Windows平台上使用gcc/g++和gdb并利用IDE调试程序的人.也希望我们谈到g++和gcc的

Eclipse 下安装 SVN的方法

http://welcome66.iteye.com/blog/1845176 eclipse里安装SVN插件,一般来说,有两种方式: 直接下载SVN插件,将其解压到eclipse的对应目录里 使用eclipse 里Help菜单的“Install New Software”,通过输入SVN地址,直接下载安装到eclipse里     第一种方式: 1.下载SVN插件 SVN插件下载地址及更新地址,你根据需要选择你需要的版本.现在最新是1.8.x Links for 1.8.x Release:

第一篇 记录下eclipse下的插件安装,查看及删除方式

eclipse下安装插件的方法: 一 .  本地安装 1. 1 直接复制 下载完成要安装的插件安装包后,解压会发现文件目录类似为以下格式 ,有没有发现该目录是和eclipse下的目录结构是一样的,然后只需要将对应目录的文件全部复制就行了,需要重启eclipse才会生效哦.(之所以说类似是因为有些插件的目录结构还真的不是这样的,例如eclipse下的,正则表达式的验证插件RegexUtil,全屏插件fullscreen就不一样,对于这两个插件的安装方法,直接复制插件包到eclipse目录下的plu

【转】Eclipse下配置CDT和MinGW终极方法。

网上关于Eclipse中配置CDT和MinGW的教程很多,但大部分都比较早,有些方法已经不适合现在的版本了.为了让那些喜爱Eclipse,计划在Eclipse平台下开发C++的爱好者不至于因为第一步没有迈开,而放弃一个绚丽多彩的Eclipse世界,我就在这介绍一些在Eclipse下配置CDT和MinGW的方法. 网上有许多介绍Eclipse配置的文章,但大多步骤较多,令人望而却步.在这里,第一部分先介绍Eclipse的安装,第二部分是CDT+MinGW的傻瓜式安装教程.第三部分是CDT+MinG

eclipse下java中注释字体太小和xml中中文字体太小问题解决方法

我们在win7下进行android应用开发,需要搭建相应的开发环境.现在普遍基本上都是eclipse+adt+sdk,在本人搭建完环境后,发现eclipse下,java中的注释和xml中的中文字体变得特别小,无法看的清楚.解决方法如下: 1.Java中字体变大方法: 打开eclipse,Window-->Preferences,如下图打开: 双击第二个红色框,如下图: 将字体改成五号即可. 2.xml中中文字体太小解决方法: 打开eclipse,Window-->Preferences--&g

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

我们在win7下进行android应用开发.须要搭建对应的开发环境.如今普遍基本上都是eclipse+adt+sdk,在本人搭建完环境后,发现eclipse下.java中的凝视和xml中的中文字体变得特别小,无法看的清楚.解决方法例如以下: 1.Java中字体变慷慨法: 打开eclipse.Window-->Preferences,例如以下图打开: 双击第二个红色框,例如以下图: 将字体改成五号就可以. 2.xml中中文字体太小解决方法: 打开eclipse.Window-->Preferen

hibernate框架在eclipse下的配置方法(一)

一.ORM O:object 对象 R:Realtion 关系(关系型数据库) M:Mapping 映射 ORM:对象关系型映射 目前流行的编程语言,如Java.C# ,它们都是面向对象的编程语言,而目前主流的数据库产品例如Oracle.DB2等,依然是关系型数据库.编程语言和底层数据库发展的不协调(阻抗不匹配,例如数据库中无法直接实现存储继承.多态.封装等特征和行为),催生出了ORM框架.ORM框架可以作为面向对象语言和关系型数据库之间的桥梁. 二.Hibernate Hibernate是一个

Eclipse下导出java程序可执行的jar包图片无法显示问题的一种解决方法

说明:在eclipse中运行java程序的时候一切正常,可是当把jar包导出的时候却发现图片没法显示,这估计是java程序的各种配置和路径问题所导致,后来找到一种解决方法,供遇到这方面问题的学习java程序的鞋同参考: Java项目下的目录结构如下: 其中class类放在包:package accpedu; (即实际是在如上bin/accpedu文件夹下面) 通过下面的方法来引用图片时,在eclipse里面执行是可以正常显示图片的: ImageIcon image1 = new ImageIco

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

这几天做了一个项目,后来因为一点原因需要修改Javaweb项目的名称,点击项目的名称->右键Refactor->Rename...  输入要修改的项目名称,保存后,部署到tomcat,突然发现eclipse下修改项目名导致tomcat内发布名不一致了 ,郁闷了,开始在网上找到解决办法,我是看 http://blog.chinaunix.net/uid-25820084-id-3531608.html 这个网站的kimutaku001的ChinaUnix博客位朋友的博客,解决了这个问题,我吧他说