Training

The types of the package Lindera that train a dictionary from an annotated corpus, as lindera dictionary train and lindera dictionary export do. A training goes in three steps:

  1. Trainer.Train trains a model (a CRF) from a seed lexicon and a corpus, and writes it to a file.
  2. Trainer.ExportModel writes the source files of a dictionary from the model.
  3. DictionaryBuilder.Build builds the dictionary from the source files.

How an error is thrown is in Lindera .NET.

The feature train

The training needs the feature train of the library, which is in the default build (see the Feature Flags of Lindera C) and in the archives of a release. A library that was built without it has the same functions: Train and ExportModel throw LinderaException of the kind Runtime, and LinderaLibrary.HasFeature("train") tells a program which library it has.

Training a model

Trainer.Train(TrainFiles files, TrainOptions? options = null) trains a model from the files and writes it to the output file. The call returns when the training is over.

TrainFiles has the paths of the six files a training reads and of the one it writes, as required properties. Every one is needed:

PropertyWhat it is
SeedThe seed lexicon: the words the dictionary starts from, as CSV
CorpusThe training corpus: text annotated with its words and their features
CharDefThe character definition (char.def)
UnkDefThe unknown word definition (unk.def)
FeatureDefThe feature definition (feature.def): the templates of the features the model learns
RewriteDefThe rewrite rules (rewrite.def)
OutputThe model file the training writes. Its directory is made if it is not there

The other settings are the properties of TrainOptions, and have defaults:

PropertyDefaultWhat it is
Lambda1.0The regularization coefficient: finite and 0 or more. 0 disables regularization for every type. With L2, MeCab's -c C is 1 / C, so 1.0 is MeCab's -c 1.0
MaxIterations100The maximum number of iterations: 1 or more. Training stops earlier once the objective converges (see Eta)
MaxThreads0The maximum number of threads. 0 is as many as the machine has CPUs
RegularizationRegularization.L2The regularization type: Regularization.L1, Regularization.L2 or Regularization.ElasticNet
ElasticNetL1Ratio0.5The L1 ratio of Elastic Net regularization: between 0 and 1. 0 uses only L2, 1 uses only L1. Used only with Regularization.ElasticNet
Eta5e-5The tolerance of the convergence test: finite and 0 or more. Training stops before the maximum number of iterations once the relative change of the objective stays below it for 3 iterations in a row. 0 disables the test

A property that is not set (null, and 0 for MaxThreads) leaves the default of the library. The package gives a Regularization to the library by the name the library takes (l1, l2 or elasticnet), which lindera dictionary train --regularization takes too.

What failsWhat is thrown
A negative MaxIterations or MaxThreads, or a Regularization that is no value of the enumerationArgumentOutOfRangeException, before the library is called
A file of TrainFiles is null or empty (seed is not set), or an option is out of its range; the message has the range (lambda must be a finite number >= 0, got -0.5)LinderaException of the kind InvalidArgument
An input file does not exist (corpus file does not exist: /path/to/corpus.txt), or the model cannot be writtenLinderaException of the kind IO
The files cannot be loaded, or the training failsLinderaException of the kind Runtime

The settings and the files are checked before the training starts, so a value out of its range or a file that is missing fails at once.

To train with the default settings of Lindera 6 (L1 with a coefficient of 0.01, and no convergence test), the options are Regularization = Regularization.L1, Lambda = 0.01 and Eta = 0.

The training writes its progress to the standard output of the process (Training with 3 examples..., Model saved to /tmp/model.dat) and a line for each iteration to its standard error, as the training functions of the other bindings do. The library writes them, not .NET: they do not go through Console.Out.

Exporting the source files of a dictionary

Trainer.ExportModel(string model, string outputDir, ExportOptions? options = null) writes the source files of a dictionary from a model, into the directory outputDir: lex.csv, matrix.def, unk.def, char.def, feature.def, rewrite.def, left-id.def and right-id.def. model is the file Train wrote.

ExportOptions.MetadataFile is the path of a metadata.json. The method updates it with the values of the model (default_word_cost, and a section model_info that records what the model was trained with) and writes it with the other files, so that the directory builds into a dictionary as it is.

The call throws LinderaException of the kind IO when the model or the metadata does not exist (Model file does not exist: /path/to/model.dat), and of the kind Runtime when the file is no model or the files cannot be written. The library lists the files it wrote on the standard output.

From a corpus to a tokenizer

The example below trains a model, exports the source files of a dictionary, builds the dictionary, and tokenizes a text with it. The repository has the files of a small training, for its tests, in resources/training:

// The training writes its progress to the standard output and
// to the standard error of the process.
string model = Path.Combine(output, "model.dat");
Trainer.Train(new TrainFiles
{
    Seed = Path.Combine(training, "seed.csv"),
    Corpus = Path.Combine(training, "corpus.txt"),
    CharDef = Path.Combine(training, "char.def"),
    UnkDef = Path.Combine(training, "unk.def"),
    FeatureDef = Path.Combine(training, "feature.def"),
    RewriteDef = Path.Combine(training, "rewrite.def"),
    Output = model,
}, new TrainOptions { MaxThreads = 1 });

// The source files of a dictionary, with the metadata.json,
// which the export updates with the values of the model.
string source = Path.Combine(output, "source");
Trainer.ExportModel(model, source, new ExportOptions { MetadataFile = Path.Combine(training, "metadata.json") });

string dictionary = Path.Combine(output, "dictionary");
using (Metadata metadata = Metadata.Load(Path.Combine(source, "metadata.json")))
{
    DictionaryBuilder.Build(source, dictionary, metadata);
}

using TokenizerBuilder builder = new TokenizerBuilder().SetDictionary(dictionary);
using Tokenizer tokenizer = builder.Build();
foreach (Token token in tokenizer.Tokenize("これは外国人参政権です。"))
{
    Console.WriteLine($"{token.Surface}\t{string.Join(',', token.Details)}");
}
Console.WriteLine("EOS");

The training and the export write their progress first, in lines that vary with the machine. What the program prints is the tokens:

これ    名詞,代名詞,一般,*,*,*,これ,コレ,コレ
は    助詞,係助詞,*,*,*,*,は,ハ,ワ
外国    名詞,一般,*,*,*,*,外国,ガイコク,ガイコク
人    名詞,接尾,一般,*,*,*,人,ジン,ジン
参政    名詞,サ変接続,*,*,*,*,参政,サンセイ,サンセイ
権    名詞,接尾,一般,*,*,*,権,ケン,ケン
です    助動詞,*,*,*,特殊・デス,基本形,です,デス,デス
。    記号,句点,*,*,*,*,。,。,。
EOS