001/** 
002 * Copyright (c) 2007-2011, Regents of the University of Colorado 
003 * All rights reserved.
004 * 
005 * Redistribution and use in source and binary forms, with or without
006 * modification, are permitted provided that the following conditions are met:
007 * 
008 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 
009 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 
010 * Neither the name of the University of Colorado at Boulder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 
011 * 
012 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
013 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
014 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
015 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
016 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
017 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
018 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
019 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
020 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
021 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
022 * POSSIBILITY OF SUCH DAMAGE. 
023 */
024package org.cleartk.examples.documentclassification.basic;
025
026import java.io.File;
027import java.util.List;
028
029import org.apache.uima.collection.CollectionReader;
030import org.cleartk.examples.documentclassification.advanced.GoldDocumentCategoryAnnotator;
031import org.cleartk.ml.jar.DefaultDataWriterFactory;
032import org.cleartk.ml.jar.DirectoryDataWriterFactory;
033import org.cleartk.ml.jar.JarClassifierBuilder;
034import org.cleartk.ml.libsvm.LibSvmStringOutcomeDataWriter;
035import org.cleartk.opennlp.tools.SentenceAnnotator;
036import org.cleartk.snowball.DefaultSnowballStemmer;
037import org.cleartk.token.tokenizer.TokenAnnotator;
038import org.cleartk.util.ae.UriToDocumentTextAnnotator;
039import org.cleartk.util.cr.UriCollectionReader;
040import org.apache.uima.fit.factory.AggregateBuilder;
041import org.apache.uima.fit.factory.AnalysisEngineFactory;
042import org.apache.uima.fit.pipeline.SimplePipeline;
043
044import com.lexicalscope.jewel.cli.CliFactory;
045import com.lexicalscope.jewel.cli.Option;
046
047/**
048 * Copyright (c) 2012, Regents of the University of Colorado <br>
049 * All rights reserved. <br>
050 * 
051 * Illustrates how to train a simple document classification annotator. For a more in-depth example
052 * that demonstrates ClearTK best practices including the use of more sophisticated feature
053 * extractors and the evaluation framework refer to the examples in
054 * org.cleartk.examples.document.classification
055 * 
056 * 
057 * @author Lee Becker
058 * 
059 */
060public class TrainModel {
061
062  public interface Options {
063    @Option(
064        longName = "train-dir",
065        description = "Specify the directory containing the training documents.  This is used for cross-validation, and for training in a holdout set evaluation. "
066            + "When we run this example we point to a directory containing training data from a subset of the 20 newsgroup corpus - i.e. a directory called '3news-bydate/train'",
067        defaultValue = "data/3news-bydate/train")
068    public File getTrainDirectory();
069
070    @Option(
071        longName = "models-dir",
072        description = "specify the directory in which to write out the trained model files",
073        defaultValue = "target/simple_document_classification/models")
074    public File getModelsDirectory();
075
076    @Option(
077        longName = "training-args",
078        description = "specify training arguments to be passed to the learner.  For multiple values specify -ta for each - e.g. '-ta -t -ta 0'",
079        defaultValue = { "-t", "0" })
080    public List<String> getTrainingArguments();
081  }
082
083  public static void main(String[] args) throws Exception {
084    Options options = CliFactory.parseArguments(Options.class, args);
085
086    // ////////////////////////////////////////
087    // Create collection reader to load URIs
088    // ////////////////////////////////////////
089    CollectionReader reader = UriCollectionReader.getCollectionReaderFromDirectory(
090        options.getTrainDirectory(),
091        UriCollectionReader.RejectSystemFiles.class,
092        UriCollectionReader.RejectSystemDirectories.class);
093
094    // ////////////////////////////////////////
095    // Create document classification pipeline
096    // ////////////////////////////////////////
097    AggregateBuilder builder = new AggregateBuilder();
098
099    // Convert URIs in CAS URI View to Plain Text
100    builder.add(UriToDocumentTextAnnotator.getDescription());
101
102    // Label documents with gold labels for training
103    builder.add(AnalysisEngineFactory.createEngineDescription(GoldDocumentCategoryAnnotator.class));
104
105    // NLP pre-processing components
106    builder.add(SentenceAnnotator.getDescription()); // Sentence segmentation
107    builder.add(TokenAnnotator.getDescription()); // Tokenization
108    builder.add(DefaultSnowballStemmer.getDescription("English")); // Stemming
109
110    // The simple document classification annotator
111    builder.add(AnalysisEngineFactory.createEngineDescription(
112        BasicDocumentClassificationAnnotator.class,
113        DefaultDataWriterFactory.PARAM_DATA_WRITER_CLASS_NAME,
114        LibSvmStringOutcomeDataWriter.class.getName(),
115        DirectoryDataWriterFactory.PARAM_OUTPUT_DIRECTORY,
116        options.getModelsDirectory()));
117
118    // ///////////////////////////////////////////
119    // Run pipeline to create training data file
120    // ///////////////////////////////////////////
121    SimplePipeline.runPipeline(reader, builder.createAggregateDescription());
122
123    // //////////////////////////////////////////////////////////////////////////////
124    // Train and write model
125    // //////////////////////////////////////////////////////////////////////////////
126    JarClassifierBuilder.trainAndPackage(
127        options.getModelsDirectory(),
128        options.getTrainingArguments().toArray(new String[options.getTrainingArguments().size()]));
129  }
130
131}