Training
The functions 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:
Traintrains a model (a CRF) from a seed lexicon and a corpus, and writes it to a file.ExportModelwrites the source files of a dictionary from the model.BuildDictionarybuilds the dictionary from the source files.
How an error is returned is in Lindera Go.
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 fail with an error of the kind KindRuntime, and lindera.HasFeature("train") tells a program which library it has.
Training a model
Train(files TrainFiles, opts ...TrainOption) error trains a model from the files and writes it to the output file. The call returns when the training is over.
TrainFiles is a struct of the paths of the six files a training reads and of the one it writes. Every one is needed:
| Field | What it is |
|---|---|
Seed | The seed lexicon: the words the dictionary starts from, as CSV |
Corpus | The training corpus: text annotated with its words and their features |
CharDef | The character definition (char.def) |
UnkDef | The unknown word definition (unk.def) |
FeatureDef | The feature definition (feature.def): the templates of the features the model learns |
RewriteDef | The rewrite rules (rewrite.def) |
Output | The model file the training writes. Its directory is made if it is not there |
The other settings are options, and have defaults:
| Option | Default | What it is |
|---|---|---|
WithLambda(lambda float64) | 1.0 | The 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 |
WithMaxIter(n int) | 100 | The maximum number of iterations: 1 or more. Training stops earlier once the objective converges (see WithEta) |
WithMaxThreads(n int) | 0 | The maximum number of threads. 0 is as many as the machine has CPUs. It is the option of the batches of a tokenizer too |
WithRegularization(regularization Regularization) | RegularizationL2 | The regularization type: RegularizationL1, RegularizationL2 or RegularizationElasticNet |
WithElasticNetL1Ratio(ratio float64) | 0.5 | The L1 ratio of Elastic Net regularization: between 0 and 1. 0 uses only L2, 1 uses only L1. Used only with RegularizationElasticNet |
WithEta(eta float64) | 5e-5 | The 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 Regularization is the name the library takes ("l1", "l2" or "elasticnet"), which lindera dictionary train --regularization takes too; the library also takes elastic_net and elastic-net, in any case.
| What fails | Kind of the error |
|---|---|
A file of TrainFiles is 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) | KindInvalidArgument |
An input file does not exist (corpus file does not exist: /path/to/corpus.txt), or the model cannot be written | KindIO |
| The files cannot be loaded, or the training fails | KindRuntime |
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 WithRegularization(lindera.RegularizationL1), WithLambda(0.01) and WithEta(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 Go: they do not go through os.Stdout.
Exporting the source files of a dictionary
ExportModel(model, outputDir string, opts ...ExportOption) error 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.
The option WithMetadataFile(path string) gives the path of a metadata.json. The function 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 fails with an error of the kind KindIO when the model or the metadata does not exist (Model file does not exist: /path/to/model.dat), and of the kind KindRuntime 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:
training := filepath.Join("..", "resources", "training")
output, err := os.MkdirTemp("", "lindera")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(output)
// The training writes its progress to the standard output and to the
// standard error of the process.
model := filepath.Join(output, "model.dat")
err = lindera.Train(lindera.TrainFiles{
Seed: filepath.Join(training, "seed.csv"),
Corpus: filepath.Join(training, "corpus.txt"),
CharDef: filepath.Join(training, "char.def"),
UnkDef: filepath.Join(training, "unk.def"),
FeatureDef: filepath.Join(training, "feature.def"),
RewriteDef: filepath.Join(training, "rewrite.def"),
Output: model,
}, lindera.WithMaxThreads(1))
if err != nil {
log.Fatal(err)
}
// The source files of a dictionary, with the metadata.json, which the
// export updates with the values of the model.
source := filepath.Join(output, "source")
err = lindera.ExportModel(model, source, lindera.WithMetadataFile(filepath.Join(training, "metadata.json")))
if err != nil {
log.Fatal(err)
}
metadata, err := lindera.LoadMetadata(filepath.Join(source, "metadata.json"))
if err != nil {
log.Fatal(err)
}
dictionary := filepath.Join(output, "dictionary")
if err := lindera.BuildDictionary(source, dictionary, metadata); err != nil {
log.Fatal(err)
}
tokenizer, err := lindera.NewTokenizerBuilder().
SetDictionary(dictionary).
Build()
if err != nil {
log.Fatal(err)
}
defer tokenizer.Close()
tokens, err := tokenizer.Tokenize("これは外国人参政権です。")
if err != nil {
log.Fatal(err)
}
for _, token := range tokens {
fmt.Printf("%s\t%s\n", token.Surface, strings.Join(token.Details, ","))
}
fmt.Println("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
The code is an example of the package (ExampleTrain in lindera-go/example_test.go), which go test runs from the directory lindera-go and whose output it compares.