edu.stanford.nlp.tagger.maxent
Class MaxentTagger

java.lang.Object
  extended by edu.stanford.nlp.tagger.maxent.MaxentTagger
All Implemented Interfaces:
ListProcessor<List<? extends HasWord>,ArrayList<TaggedWord>>, Function<List<? extends HasWord>,ArrayList<TaggedWord>>

public class MaxentTagger
extends Object
implements Function<List<? extends HasWord>,ArrayList<TaggedWord>>, ListProcessor<List<? extends HasWord>,ArrayList<TaggedWord>>

The main class for users to run, train, and test the part of speech tagger. You can tag things through the Java API or from the command line. The two English taggers included in this distribution are:

Using the Java API

A MaxentTagger can be made with a constructor taking as argument the location of parameter files for a trained tagger:
MaxentTagger tagger = new MaxentTagger("models/left3words-wsj-0-18.tagger");

A default path is provided for the location of the tagger on the Stanford NLP machines:
MaxentTagger tagger = new MaxentTagger(DEFAULT_NLP_GROUP_MODEL_PATH);

If you set the NLP_DATA_HOME environment variable, DEFAULT_NLP_GROUP_MODEL_PATH will instead point to the directory given in NLP_DATA_HOME.

To tag a Sentence and get a TaggedSentence:
Sentence taggedSentence = tagger.tagSentence(Sentence sentence)
Sentence taggedSentence = tagger.apply(Sentence sentence)

To tag a list of sentences and get back a list of tagged sentences:
List taggedList = tagger.process(List sentences)

To tag a String of text and to get back a String with tagged words:
String taggedString = tagger.tagString("Here's a tagged string.")

To tag a string of correctly tokenized, whitespace-separated words and get a string of tagged words back:
String taggedString = tagger.tagTokenizedString("Here 's a tagged string .")

The tagString method uses the default tokenizer (PTBTokenizer). If you wish to control tokenization, you may wish to call tokenizeText(Reader, TokenizerFactory) and then to call process() on the result.

Using the command line

Tagging, testing, and training can all also be done via the command line.

Training from the command line

To train a model from the command line, first generate a property file:
java edu.stanford.nlp.tagger.maxent.MaxentTagger -genprops 
This gets you a default properties file with descriptions of each parameter you can set in your trained model. You can modify the properties file , or use the default options. To train, run:
java -mx1g edu.stanford.nlp.tagger.maxent.MaxentTagger -props myPropertiesFile.props 
with the appropriate properties file specified; any argument you give in the properties file can also be specified on the command line. You must have specified a model using -model, either in the properties file or on the command line, as well as a file containing tagged words using -trainFile. Useful flags for controlling the amount of output are -verbose, which prints extra debugging information, and -verboseResults, which prints full information about intermediate results. -verbose defaults to false and -verboseResults defaults to true.

Tagging and Testing from the command line

Usage: For tagging (plain text):
java edu.stanford.nlp.tagger.maxent.MaxentTagger -model <modelFile> -textFile <textfile> 
For testing (evaluating against tagged text):
java edu.stanford.nlp.tagger.maxent.MaxentTagger -model <modelFile> -testFile <testfile> 
You can use the same properties file as for training if you pass it in with the "-props" argument. The most important arguments for tagging (besides "model" and "file") are "tokenize" and "tokenizerFactory". See below for more details.
Note that the tagger assumes input has not yet been tokenized and by default tokenizes it using a default English tokenizer. If your input has already been tokenized, use the flag "-tokenize false".

Parameters can be defined using a Properties file (specified on the command-line with -prop propFile), or directly on the command line (by preceding their name with a minus sign ("-") to turn them into a flag. The following properties are recognized:

Property NameTypeDefault ValueRelevant Phase(s)Description
modelStringN/AAllPath and filename where you would like to save the model (training) or where the model should be loaded from (testing, tagging).
trainFileStringN/ATrain Path to the file holding the training data; specifying this option puts the tagger in training mode. Only one of 'trainFile','testFile','textFile', and 'convertToSingleFile' may be specified.
There are two formats possible. The first is a text file of tagged data, Each line is considered a separate sentence. In each sentence, words are separated by whitespace. Each word must have a tag, which is separated using the specified tagSeparator. This format is the default format.
The other possible format is a file of Penn Treebank formatted tree files. Trees are loaded one at a time and the tagged words in the tree are used as the training sentence. To specify this format, preface the filename with "format=TREES,".
A file can be a different encoding than the tagger's default encoding by prefacing the filename with "encoding=ENC".
Tree files can be fed through TreeTransformers and TreeNormalizers. To specify a transformer, preface the filename with "treeTransformer=CLASSNAME". To specify a normalizer, preface the filename with "treeNormalizer=CLASSNAME". A specific range of trees to be used can be specified with treeRange=X-Y.
Multiple files can be specified by making a semicolon separated list of files. Each file can have its own format specifiers as above.
You will note that none of , ; or = can be in filenames.
testFileStringN/ATestPath to the file holding the test data; specifying this option puts the tagger in testing mode. Only one of 'trainFile','testFile','textFile', and 'convertToSingleFile' may be specified. The same format as trainFile applies, but only one file can be specified.
textFileStringN/ATagPath to the file holding the text to tag; specifying this option puts the tagger in tagging mode. Only one of 'trainFile','testFile','textFile', and 'convertToSingleFile' may be specified. No file reading options may be specified for textFile
convertToSingleFileStringN/AN/AProvided only for backwards compatibility, this option allows you to convert a tagger trained using a previous version of the tagger to the new single-file format. The value of this flag should be the path for the new model file, 'model' should be the path prefix to the old tagger (up to but not including the ".holder"), and you should supply the properties configuration for the old tagger with -props (before these two arguments).
genpropsbooleanN/AN/AUse this option to output a default properties file, containing information about each of the possible configuration options.
tagSeparatorchar/AllSeparator character that separates word and part of speech tags, such as out/IN or out_IN. For training and testing, this is the separator used in the train/test files. For tagging, this is the character that will be inserted between words and tags in the output.
encodingStringUTF-8AllEncoding of the read files (training, testing) and the output text files.
tokenizebooleantrueTag,TestWhether or not the file needs to be tokenized. If this is false, the tagger assumes that white space separates words if and only if they should be tagged as separate tokens, and that the input is strictly one sentence per line.
tokenizerFactoryStringedu.stanford.nlp.
process.PTBTokenizer
Tag,TestFully qualified class name of the tokenizer to use. edu.stanford.nlp.process.PTBTokenizer does basic English tokenization.
tokenizerOptionsStringTag,TestKnown options for the particular tokenizer used. A comma-separated list. For PTBTokenizer, options of interest include americanize=false and asciiQuotes (for German). Note that any choice of tokenizer options that conflicts with the tokenization used in the tagger training data will likely degrade tagger performance.
archStringgenericTrainArchitecture of the model, as a comma-separated list of options, some with a parenthesized integer argument written k here: this determines what features are sed to build your model. Options are 'left3words', 'left5words', 'bidirectional', 'bidirectional5words', generic', 'sighan2005' (Chinese), 'german', 'words(k),' 'naacl2003unknowns', 'naacl2003conjunctions', wordshapes(k), motleyUnknown, suffix(k), prefix(k), prefixsuffix(k), capitalizationsuffix(k), distsim(s), chinesedictionaryfeatures(s), lctagfeatures, unicodeshapes(k). The left3words architectures are faster, but slightly less accurate, than the bidirectional architectures. 'naacl2003unknowns' was our traditional set of unknown word features, but you can now specify features more flexibility via the various other supported keywords. The 'shapes' options map words to equivalence classes, which slightly increase accuracy.
langStringenglishTrainLanguage from which the part of speech tags are drawn. This option determines which tags are considered closed-class (only fixed set of words can be tagged with a closed-class tag, such as prepositions). Defined languages are 'english' (Penn tagset), 'polish' (very rudimentary), 'chinese', 'arabic', 'german', and 'medline'.
openClassTagsStringN/ATrainSpace separated list of tags that should be considered open-class. All tags encountered that are not in this list are considered closed-class. E.g. format: "NN VB"
closedClassTagsStringN/ATrainSpace separated list of tags that should be considered closed-class. All tags encountered that are not in this list are considered open-class.
learnClosedClassTagsbooleanfalseTrainIf true, induce which tags are closed-class by counting as closed-class tags all those tags which have fewer unique word tokens than closedClassTagThreshold.
closedClassTagThresholdintintTrainNumber of unique word tokens that a tag may have and still be considered closed-class; relevant only if learnClosedClassTags is true.
sgmlbooleanfalseTag, TestVery basic tagging of the contents of all sgml fields; for more complex mark-up, consider using the xmlInput option.
xmlInputStringTag, TestGive a space separated list of tags in an XML file whose content you would like tagged. Any internal tags that appear in the content of fields you would like tagged will be discarded; the rest of the XML will be preserved and the original text of specified fields will be replaced with the tagged text.
outputFileString""TagPath to write output to. If blank, stdout is used.
outputFormatString""TagOutput format. One of: slashTags (default), xml, or tsv
outputFormatOptionsString""TagOutput format options.
tagInsideString""TagTags inside elements that match the regular expression given in the String.
searchStringcgTrainSpecify the search method to be used in the optimization method for training. Options are 'cg' (conjugate gradient) or 'iis' (improved iterative scaling).
sigmaSquareddouble0.5TrainSigma-squared smoothing/regularization parameter to be used for conjugate gradient search. Default usually works reasonably well.
iterationsint100TrainNumber of iterations to be used for improved iterative scaling.
rareWordThreshint5TrainWords that appear fewer than this number of times during training are considered rare words and use extra rare word features.
minFeatureThresholdint5TrainFeatures whose history appears fewer than this number of times are discarded.
curWordMinFeatureThresholdint2TrainWords that occur more than this number of times will generate features with all of the tags they've been seen with.
rareWordMinFeatureThreshint10TrainFeatures of rare words whose histories occur fewer than this number of times are discarded.
veryCommonWordThreshint250TrainWords that occur more than this number of times form an equivalence class by themselves. Ignored unless you are using ambiguity classes.
debugbooleanbooleanAllWhether to write debugging information (words, top words, unknown words). Useful for error analysis.
debugPrefixStringN/AAllFile (path) prefix for where to write out the debugging information (relevant only if debug=true).

Author:
Kristina Toutanova, Miler Lee, Joseph Smarr, Anna Rafferty, Michel Galley, Christopher Manning, John Bauer

Field Summary
static String BASE_TAGGER_HOME
          The directory from which to get taggers when using DEFAULT_NLP_GROUP_MODEL_PATH.
static String DEFAULT_DISTRIBUTION_PATH
           
static String DEFAULT_NLP_GROUP_MODEL_PATH
           
static String TAGGER_HOME
           
 
Constructor Summary
MaxentTagger()
           
MaxentTagger(String modelFile)
          Constructor for a tagger using a model stored in a particular file.
MaxentTagger(String modelFile, TaggerConfig config)
          Constructor for a tagger using a model stored in a particular file, with options taken from the supplied TaggerConfig.
MaxentTagger(String modelFile, TaggerConfig config, boolean printLoading)
          Initializer that loads the tagger.
 
Method Summary
 ArrayList<TaggedWord> apply(List<? extends HasWord> in)
          Expects a sentence and returns a tagged sentence.
protected  TokenizerFactory<? extends HasWord> chooseTokenizerFactory()
          Figures out what tokenizer factory might be described by the config.
protected static TokenizerFactory<? extends HasWord> chooseTokenizerFactory(boolean tokenize, String tokenizerFactory, String tokenizerOptions, boolean invertible)
           
protected  void dumpModel(PrintStream out)
           
 TTags getTags()
           
static void lemmatize(List<CoreLabel> sentence, Morphology morpha)
          Adds lemmas to the given list of CoreLabels, using the given Morphology object.
static void main(String[] args)
          Command-line tagger interface.
 List<ArrayList<TaggedWord>> process(List<? extends List<? extends HasWord>> sentences)
          Tags the Words in each Sentence in the given List with their grammatical part-of-speech.
protected  void readModelAndInit(TaggerConfig config, DataInputStream rf, boolean printLoading)
          This reads the complete tagger from a single model file, and inits the tagger using a combination of the properties passed in and parameters from the file.
protected  void readModelAndInit(TaggerConfig config, String modelFileOrUrl, boolean printLoading)
          This reads the complete tagger from a single model stored in a file, at a URL, or as a resource in a jar file, and inits the tagger using a combination of the properties passed in and parameters from the file.
 void runTagger(BufferedReader reader, BufferedWriter writer, String tagInside, boolean stdin)
          This method runs the tagger on the provided reader & writer.
protected  void saveModel(String filename, TaggerConfig config)
           
 void tagCoreLabels(List<CoreLabel> sentence)
          Takes a sentence composed of CoreLabels and add the tags to the CoreLabels, modifying the input sentence.
 void tagFromXML(InputStream input, Writer writer, String... xmlTags)
          Uses an XML transformer to turn an input stream into a bunch of output.
 void tagFromXML(Reader input, Writer writer, String... xmlTags)
           
 ArrayList<TaggedWord> tagSentence(List<? extends HasWord> sentence)
          Returns a new Sentence that is a copy of the given sentence with all the words tagged with their part-of-speech.
 String tagString(String toTag)
          Tags the input string and returns the tagged version.
 String tagTokenizedString(String toTag)
          Tags the tokenized input string and returns the tagged version.
static List<List<HasWord>> tokenizeText(Reader r)
          Reads data from r, tokenizes it with the default (Penn Treebank) tokenizer, and returns a List of Sentence objects, which can then be fed into tagSentence.
protected static List<List<HasWord>> tokenizeText(Reader r, TokenizerFactory<? extends HasWord> tokenizerFactory)
          Reads data from r, tokenizes it with the given tokenizer, and returns a List of Lists of (extends) HasWord objects, which can then be fed into tagSentence.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

BASE_TAGGER_HOME

public static final String BASE_TAGGER_HOME
The directory from which to get taggers when using DEFAULT_NLP_GROUP_MODEL_PATH. Normally set to the location of the latest left3words tagger on the NLP machines, but can be changed by setting the environment variable NLP_DATA_HOME.

See Also:
Constant Field Values

TAGGER_HOME

public static final String TAGGER_HOME

DEFAULT_NLP_GROUP_MODEL_PATH

public static final String DEFAULT_NLP_GROUP_MODEL_PATH

DEFAULT_DISTRIBUTION_PATH

public static final String DEFAULT_DISTRIBUTION_PATH
See Also:
Constant Field Values
Constructor Detail

MaxentTagger

public MaxentTagger()

MaxentTagger

public MaxentTagger(String modelFile)
             throws IOException,
                    ClassNotFoundException
Constructor for a tagger using a model stored in a particular file. The modelFile is a filename for the model data. The tagger data is loaded when the constructor is called (this can be slow). This constructor first constructs a TaggerConfig object, which loads the tagger options from the modelFile.

Parameters:
modelFile - filename of the trained model
Throws:
IOException - if IO problem
ClassNotFoundException - when there are errors loading a tagger

MaxentTagger

public MaxentTagger(String modelFile,
                    TaggerConfig config)
             throws IOException,
                    ClassNotFoundException
Constructor for a tagger using a model stored in a particular file, with options taken from the supplied TaggerConfig. The modelFile is a filename for the model data. The tagger data is loaded when the constructor is called (this can be slow). This version assumes that the tagger options in the modelFile have already been loaded into the TaggerConfig (if that is desired).

Parameters:
modelFile - filename of the trained model
config - The configuration for the tagger
Throws:
IOException - if IO problem
ClassNotFoundException - when there are errors loading a tagger

MaxentTagger

public MaxentTagger(String modelFile,
                    TaggerConfig config,
                    boolean printLoading)
             throws IOException,
                    ClassNotFoundException
Initializer that loads the tagger.

Parameters:
modelFile - Where to initialize the tagger from. Most commonly, this is the filename of the trained model, for example, /u/nlp/data/pos-tagger/wsj3t0-18-left3words/left3words-wsj-0-18.tagger . However, if it starts with "https?://" it will be interpreted as a URL, and if it starts with "jar:" it will be taken as a resources in the /models/ path of the current jar file.
config - TaggerConfig based on command-line arguments
printLoading - Whether to print a message saying what model file is being loaded and how long it took when finished.
Throws:
IOException - if IO problem
ClassNotFoundException - when there are errors loading a tagger
Method Detail

chooseTokenizerFactory

protected TokenizerFactory<? extends HasWord> chooseTokenizerFactory()
                                                              throws ClassNotFoundException,
                                                                     NoSuchMethodException,
                                                                     IllegalAccessException,
                                                                     InvocationTargetException
Figures out what tokenizer factory might be described by the config. If it's described by name in the config, uses reflection to get the factory (which may cause an exception, of course...)

Throws:
ClassNotFoundException
NoSuchMethodException
IllegalAccessException
InvocationTargetException

chooseTokenizerFactory

protected static TokenizerFactory<? extends HasWord> chooseTokenizerFactory(boolean tokenize,
                                                                            String tokenizerFactory,
                                                                            String tokenizerOptions,
                                                                            boolean invertible)
                                                                     throws ClassNotFoundException,
                                                                            NoSuchMethodException,
                                                                            IllegalAccessException,
                                                                            InvocationTargetException
Throws:
ClassNotFoundException
NoSuchMethodException
IllegalAccessException
InvocationTargetException

saveModel

protected void saveModel(String filename,
                         TaggerConfig config)

readModelAndInit

protected void readModelAndInit(TaggerConfig config,
                                String modelFileOrUrl,
                                boolean printLoading)
                         throws IOException,
                                ClassNotFoundException
This reads the complete tagger from a single model stored in a file, at a URL, or as a resource in a jar file, and inits the tagger using a combination of the properties passed in and parameters from the file.

Note for the future: This assumes that the TaggerConfig in the file has already been read and used. This work is done inside the constructor of TaggerConfig. It might be better to refactor things so that is all done inside this method, but for the moment it seemed better to leave working code alone [cdm 2008].

Parameters:
config - The tagger config
modelFileOrUrl - The name of the model file. This routine opens and closes it.
printLoading - Whether to print a message saying what model file is being loaded and how long it took when finished.
Throws:
IOException - If I/O errors, etc.
ClassNotFoundException - especially for incompatible tagger formats

readModelAndInit

protected void readModelAndInit(TaggerConfig config,
                                DataInputStream rf,
                                boolean printLoading)
                         throws IOException,
                                ClassNotFoundException
This reads the complete tagger from a single model file, and inits the tagger using a combination of the properties passed in and parameters from the file.

Note for the future: This assumes that the TaggerConfig in the file has already been read and used. It might be better to refactor things so that is all done inside this method, but for the moment it seemed better to leave working code alone [cdm 2008].

Parameters:
config - The tagger config
rf - DataInputStream to read from. It's the caller's job to open and close this stream.
printLoading - Whether to print a message saying what model file is being loaded and how long it took when finished.
Throws:
IOException - If I/O errors
ClassNotFoundException - If serialization errors

dumpModel

protected void dumpModel(PrintStream out)

getTags

public TTags getTags()

tagTokenizedString

public String tagTokenizedString(String toTag)
Tags the tokenized input string and returns the tagged version. This method requires the input to already be tokenized. The tagger wants input that is whitespace separated tokens, tokenized according to the conventions of the training data. (For instance, for the Penn Treebank, punctuation marks and possessive "'s" should be separated from words.)

Parameters:
toTag - The untagged input String
Returns:
The same string with tags inserted in the form word/tag

tagString

public String tagString(String toTag)
Tags the input string and returns the tagged version. This method tokenizes the input into words in perhaps multiple sentences and then tags those sentences. The default (PTB English) tokenizer is used.

Parameters:
toTag - The untagged input String
Returns:
A String of sentences with tags inserted in the form word/tag

apply

public ArrayList<TaggedWord> apply(List<? extends HasWord> in)
Expects a sentence and returns a tagged sentence. The input Sentence items

Specified by:
apply in interface Function<List<? extends HasWord>,ArrayList<TaggedWord>>
Parameters:
in - This needs to be a Sentence
Returns:
A Sentence of TaggedWord

process

public List<ArrayList<TaggedWord>> process(List<? extends List<? extends HasWord>> sentences)
Tags the Words in each Sentence in the given List with their grammatical part-of-speech. The returned List contains Sentences consisting of TaggedWords.

NOTE: The input document must contain sentences as its elements, not words. To turn a Document of words into a Document of sentences, run it through WordToSentenceProcessor.

Specified by:
process in interface ListProcessor<List<? extends HasWord>,ArrayList<TaggedWord>>
Parameters:
sentences - A List of Sentence
Returns:
A List of Sentence of TaggedWord (final generification cannot be listed due to lack of complete generification of super classes)

tagSentence

public ArrayList<TaggedWord> tagSentence(List<? extends HasWord> sentence)
Returns a new Sentence that is a copy of the given sentence with all the words tagged with their part-of-speech. Convenience method when you only want to tag a single List instead of a Document of sentences.

Parameters:
sentence - sentence to tag
Returns:
tagged sentence

tagCoreLabels

public void tagCoreLabels(List<CoreLabel> sentence)
Takes a sentence composed of CoreLabels and add the tags to the CoreLabels, modifying the input sentence.


lemmatize

public static void lemmatize(List<CoreLabel> sentence,
                             Morphology morpha)
Adds lemmas to the given list of CoreLabels, using the given Morphology object. The input list must already have tags set.


tokenizeText

public static List<List<HasWord>> tokenizeText(Reader r)
Reads data from r, tokenizes it with the default (Penn Treebank) tokenizer, and returns a List of Sentence objects, which can then be fed into tagSentence.

Parameters:
r - Reader where untokenized text is read
Returns:
List of tokenized sentences

tokenizeText

protected static List<List<HasWord>> tokenizeText(Reader r,
                                                  TokenizerFactory<? extends HasWord> tokenizerFactory)
Reads data from r, tokenizes it with the given tokenizer, and returns a List of Lists of (extends) HasWord objects, which can then be fed into tagSentence.

Parameters:
r - Reader where untokenized text is read
tokenizerFactory - Tokenizer. This can be null in which case the default English tokenizer (PTBTokenizerFactory) is used.
Returns:
List of tokenized sentences

tagFromXML

public void tagFromXML(InputStream input,
                       Writer writer,
                       String... xmlTags)
Uses an XML transformer to turn an input stream into a bunch of output. Tags all of the text between xmlTags. The difference between using this and using runTagger in XML mode is that this preserves the XML structure outside of the list of elements to tag, whereas the runTagger method throws away all of the surrounding structure and returns tagged plain text.


tagFromXML

public void tagFromXML(Reader input,
                       Writer writer,
                       String... xmlTags)

runTagger

public void runTagger(BufferedReader reader,
                      BufferedWriter writer,
                      String tagInside,
                      boolean stdin)
               throws IOException,
                      ClassNotFoundException,
                      NoSuchMethodException,
                      IllegalAccessException,
                      InvocationTargetException
This method runs the tagger on the provided reader & writer. It takes into from the given reader, applies the tagger to it one sentence at a time (determined using documentPreprocessor), and writes the output to the given writer. The document is broken into sentences using the sentence processor determined in the tagger's TaggerConfig. tagInside makes the tagger run in XML mode... if set to non-empty, instead of processing the document as one large text blob, it considers each region in between the given tag to be a separate text blob. stdin makes the tagger take lines one at a time from the reader and print out a bit more nice formatting to the writer. It doesn't actually require the reader to be stdin, though. This is mutually exclusive with tagInside; if tagInside is not empty, stdin will be ignored.

Throws:
IOException
ClassNotFoundException
NoSuchMethodException
IllegalAccessException
InvocationTargetException

main

public static void main(String[] args)
                 throws Exception
Command-line tagger interface. Can be used to train or test taggers, or to tag text, taking input from stdin or a file. See class documentation for usage.

Parameters:
args - Command-line arguments
Throws:
IOException - If any file problems
Exception


Stanford NLP Group