Training
The functions of lindera.h that train a dictionary from an annotated corpus, as lindera dictionary train and lindera dictionary export do. A training goes in three steps:
lindera_trainer_traintrains a model (a CRF) from a seed lexicon and a corpus, and writes it to a file.lindera_trainer_exportwrites the source files of a dictionary from the model.lindera_dictionary_buildbuilds the dictionary from the source files.
The rules the functions share (who frees an object, how an error is returned, how text is passed) are in Lindera C. In the prototypes below, text is a pair of arguments, const uint8_t *ptr, size_t len: len bytes of UTF-8, with no NUL needed at the end. A path is text.
The feature train
The training needs the feature train, which is in the default build of the library (see Feature Flags). A library that was built without it has the same functions: lindera_trainer_train, lindera_trainer_export and lindera_trainer_config_set_regularization fail with LINDERA_STATUS_RUNTIME, and lindera_has_feature tells a program which library it has ("train").
LinderaTrainerConfig
The settings of a training: the files it reads and writes, and how it regularizes and stops.
LinderaTrainerConfig *lindera_trainer_config_new(void);
void lindera_trainer_config_free(LinderaTrainerConfig *config);
lindera_trainer_config_new makes settings with the default values, and no file. The caller frees them with lindera_trainer_config_free.
A training reads six files and writes one. Each has a function that sets its path, lindera_trainer_config_set_<file>, with the arguments of this one:
LinderaStatus lindera_trainer_config_set_seed(LinderaTrainerConfig *config, const uint8_t *path,
size_t path_len, LinderaError **error);
| File | 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 |
char_def | The character definition (char.def) |
unk_def | The unknown word definition (unk.def) |
feature_def | The feature definition (feature.def): the templates of the features the model learns |
rewrite_def | The rewrite rules (rewrite.def) |
output | The model file the training writes. Its directory is made if it is not there |
The empty text (NULL, 0) takes a file out of the settings.
The other settings have defaults:
LinderaStatus lindera_trainer_config_set_lambda(LinderaTrainerConfig *config, double lambda,
LinderaError **error);
LinderaStatus lindera_trainer_config_set_max_iter(LinderaTrainerConfig *config, uint64_t max_iter,
LinderaError **error);
LinderaStatus lindera_trainer_config_set_max_threads(LinderaTrainerConfig *config,
size_t max_threads, LinderaError **error);
LinderaStatus lindera_trainer_config_set_regularization(LinderaTrainerConfig *config,
const uint8_t *name, size_t name_len,
LinderaError **error);
LinderaStatus lindera_trainer_config_set_elastic_net_l1_ratio(LinderaTrainerConfig *config,
double ratio, LinderaError **error);
LinderaStatus lindera_trainer_config_set_eta(LinderaTrainerConfig *config, double eta,
LinderaError **error);
| Setting | Default | What it is |
|---|---|---|
lambda | 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 |
max_iter | 100 | The maximum number of iterations: 1 or more. Training stops earlier once the objective converges (see eta) |
max_threads | 0 | The maximum number of threads. 0 is as many as the machine has CPUs |
regularization | l2 | The regularization type, by its name: l1, l2 or elasticnet, in any case (elastic_net and elastic-net are Elastic Net too), as lindera dictionary train --regularization takes it |
elastic_net_l1_ratio | 0.5 | The L1 ratio of Elastic Net regularization: between 0 and 1. 0 uses only L2, 1 uses only L1. Used only with elasticnet |
eta | 5e-5 | The tolerance of the convergence test: finite and 0 or more. Training stops before max_iter once the relative change of the objective stays below it for 3 iterations in a row. 0 disables the test |
A value outside its range, and a name that is no regularization, fail with LINDERA_STATUS_INVALID_ARGUMENT when they are set, and change nothing. The message has the range (lambda must be a finite number >= 0, got -0.5).
To train with the default settings of Lindera 6 (L1 with a coefficient of 0.01, and no convergence test):
lindera_trainer_config_set_regularization(config, (const uint8_t *)"l1", 2, &error);
lindera_trainer_config_set_lambda(config, 0.01, &error);
lindera_trainer_config_set_eta(config, 0.0, &error);
Training a model
LinderaStatus lindera_trainer_train(const LinderaTrainerConfig *config, LinderaError **error);
lindera_trainer_train trains a model from the files of the settings and writes it to their output file. The call returns when the training is over.
| What fails | Status |
|---|---|
config is NULL, or one of the seven files is not set (seed is not set) | LINDERA_STATUS_INVALID_ARGUMENT |
An input file does not exist (corpus file does not exist: /path/to/corpus.txt), or the model cannot be written | LINDERA_STATUS_IO |
| The files cannot be loaded, or the training fails | LINDERA_STATUS_RUNTIME |
The files are checked before the training starts, so a file that is missing fails at once.
The training writes its progress to the standard output (Training with 3 examples..., Model saved to /tmp/model.dat) and a line for each iteration to the standard error, as the training functions of the other bindings do.
Exporting the source files of a dictionary
LinderaStatus lindera_trainer_export(const uint8_t *model, size_t model_len,
const uint8_t *output_dir, size_t output_dir_len,
const uint8_t *metadata, size_t metadata_len,
LinderaError **error);
lindera_trainer_export writes the source files of a dictionary from a model, into the directory output_dir: lex.csv, matrix.def, unk.def, char.def, feature.def, rewrite.def, left-id.def and right-id.def. model is the file lindera_trainer_train wrote.
metadata is the path of a metadata.json, or the empty text (NULL, 0) for none. With one, 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 LINDERA_STATUS_IO when the model or the metadata does not exist (Model file does not exist: /path/to/model.dat), and with LINDERA_STATUS_RUNTIME when the file is no model or the files cannot be written. It lists the files it wrote on the standard output.
From a corpus to a tokenizer
The program below is lindera-c/examples/train_dictionary.c. It trains a model, exports the source files of a dictionary, builds the dictionary, and tokenizes a text with it:
/* Trains a model from an annotated corpus, exports the source files of a
* dictionary from it, builds the dictionary, and tokenizes a text with it:
* what `lindera dictionary train`, `export` and `build` do.
*
* train_dictionary <training directory> <output directory> [<text>]
*
* <training directory> holds seed.csv, corpus.txt, char.def, unk.def,
* feature.def, rewrite.def and metadata.json. The model (model.dat), the
* source files (source/) and the dictionary (dictionary/) are written under
* <output directory>. <text> is UTF-8.
*/
#include <stdio.h>
#include <string.h>
#include "lindera.h"
/* The longest path this program builds. */
#define PATH_SIZE 4096
/* Prints what failed with the message of the error, frees the error, and
* returns the exit code of a failure. */
static int fail(const char *what, LinderaStatus status, LinderaError *error) {
LinderaStr message = lindera_error_message(error);
fprintf(stderr, "%s: %s: %.*s\n", what, lindera_status_name(status), (int)message.len,
(const char *)message.ptr);
lindera_error_free(error);
return 1;
}
/* Writes `<dir>/<name>` to `path`, which has PATH_SIZE bytes, and returns
* its length. A path that does not fit is the empty text, which the library
* refuses where it needs a file. */
static size_t join(char *path, const char *dir, const char *name) {
int length = snprintf(path, PATH_SIZE, "%s/%s", dir, name);
if (length < 0 || length >= PATH_SIZE) {
path[0] = '\0';
return 0;
}
return (size_t)length;
}
/* Trains a model from the files of `training` and writes it to `model`. */
static LinderaStatus train(const char *training, const char *model, LinderaError **error) {
LinderaTrainerConfig *config = lindera_trainer_config_new();
LinderaStatus status = LINDERA_STATUS_OK;
char path[PATH_SIZE];
size_t len;
/* The six files a training reads, and the one it writes. */
len = join(path, training, "seed.csv");
status = lindera_trainer_config_set_seed(config, (const uint8_t *)path, len, error);
if (status == LINDERA_STATUS_OK) {
len = join(path, training, "corpus.txt");
status = lindera_trainer_config_set_corpus(config, (const uint8_t *)path, len, error);
}
if (status == LINDERA_STATUS_OK) {
len = join(path, training, "char.def");
status = lindera_trainer_config_set_char_def(config, (const uint8_t *)path, len, error);
}
if (status == LINDERA_STATUS_OK) {
len = join(path, training, "unk.def");
status = lindera_trainer_config_set_unk_def(config, (const uint8_t *)path, len, error);
}
if (status == LINDERA_STATUS_OK) {
len = join(path, training, "feature.def");
status = lindera_trainer_config_set_feature_def(config, (const uint8_t *)path, len, error);
}
if (status == LINDERA_STATUS_OK) {
len = join(path, training, "rewrite.def");
status = lindera_trainer_config_set_rewrite_def(config, (const uint8_t *)path, len, error);
}
if (status == LINDERA_STATUS_OK) {
status = lindera_trainer_config_set_output(config, (const uint8_t *)model, strlen(model), error);
}
/* The other settings have defaults: L2 regularization with a coefficient
* of 1.0, and at most 100 iterations, which is set here to show how. */
if (status == LINDERA_STATUS_OK) {
status = lindera_trainer_config_set_max_iter(config, 100, error);
}
if (status == LINDERA_STATUS_OK) {
status = lindera_trainer_train(config, error);
}
lindera_trainer_config_free(config);
return status;
}
int main(int argc, char **argv) {
const char *text = argc > 3 ? argv[3] : "これは外国人参政権です。";
const char *training;
const char *output;
char model[PATH_SIZE];
char source[PATH_SIZE];
char built[PATH_SIZE];
char path[PATH_SIZE];
size_t len;
LinderaMetadata *metadata = NULL;
LinderaDictionary *dictionary = NULL;
LinderaTokenizer *tokenizer = NULL;
LinderaResult *result = NULL;
LinderaTokens tokens;
LinderaError *error = NULL;
LinderaStatus status;
size_t i;
size_t j;
if (argc < 3) {
fprintf(stderr, "usage: train_dictionary <training directory> <output directory> [<text>]\n");
return 2;
}
training = argv[1];
output = argv[2];
/* A library can be built without the training. */
if (!lindera_has_feature((const uint8_t *)"train", 5)) {
fprintf(stderr, "this library was built without the feature train\n");
return 1;
}
join(model, output, "model.dat");
join(source, output, "source");
join(built, output, "dictionary");
/* 1. Train the model. */
status = train(training, model, &error);
if (status != LINDERA_STATUS_OK) {
return fail("training", status, error);
}
/* 2. Export the source files of a dictionary from the model, with the
* metadata.json of the training updated for them. */
len = join(path, training, "metadata.json");
status = lindera_trainer_export((const uint8_t *)model, strlen(model), (const uint8_t *)source,
strlen(source), (const uint8_t *)path, len, &error);
if (status != LINDERA_STATUS_OK) {
return fail("lindera_trainer_export", status, error);
}
/* 3. Build the dictionary from the source files, with the metadata that
* was exported with them. */
len = join(path, source, "metadata.json");
status = lindera_metadata_from_json_file((const uint8_t *)path, len, &metadata, &error);
if (status != LINDERA_STATUS_OK) {
return fail("lindera_metadata_from_json_file", status, error);
}
status = lindera_dictionary_build((const uint8_t *)source, strlen(source), (const uint8_t *)built,
strlen(built), metadata, NULL, 0, &error);
lindera_metadata_free(metadata);
if (status != LINDERA_STATUS_OK) {
return fail("lindera_dictionary_build", status, error);
}
/* 4. Tokenize with the dictionary. */
status = lindera_dictionary_load((const uint8_t *)built, strlen(built), &dictionary, &error);
if (status != LINDERA_STATUS_OK) {
return fail("lindera_dictionary_load", status, error);
}
status = lindera_tokenizer_new(dictionary, NULL, NULL, NULL, 0, &tokenizer, &error);
lindera_dictionary_free(dictionary);
if (status != LINDERA_STATUS_OK) {
return fail("lindera_tokenizer_new", status, error);
}
status = lindera_tokenizer_tokenize(tokenizer, (const uint8_t *)text, strlen(text), &result,
&tokens, &error);
if (status != LINDERA_STATUS_OK) {
lindera_tokenizer_free(tokenizer);
return fail("lindera_tokenizer_tokenize", status, error);
}
for (i = 0; i < tokens.len; i++) {
const LinderaToken *token = &tokens.tokens[i];
printf("%.*s\t", (int)token->surface.len, (const char *)token->surface.ptr);
for (j = 0; j < token->details_len; j++) {
printf("%s%.*s", j == 0 ? "" : ",", (int)token->details[j].len,
(const char *)token->details[j].ptr);
}
printf("\n");
}
printf("EOS\n");
lindera_result_free(result);
lindera_tokenizer_free(tokenizer);
return 0;
}
Compile it against an installed library (see Installation) and run it with the directory of the training files and a directory to write to. The repository has the files of a small training, for its tests:
export PKG_CONFIG_PATH="$PWD/dist/lib/pkgconfig"
cc -o train_dictionary lindera-c/examples/train_dictionary.c $(pkg-config --cflags --libs lindera)
LD_LIBRARY_PATH="$PWD/dist/lib" ./train_dictionary resources/training /tmp/lindera-example-training
The training writes its progress first, in lines that vary with the machine. The output ends with the files that were written and the tokens:
Model saved to /tmp/lindera-example-training/model.dat
Updated metadata.json with trained model values
Dictionary files exported to: /tmp/lindera-example-training/source
Files created:
- /tmp/lindera-example-training/source/lex.csv
- /tmp/lindera-example-training/source/matrix.def
- /tmp/lindera-example-training/source/unk.def
- /tmp/lindera-example-training/source/char.def
- /tmp/lindera-example-training/source/feature.def
- /tmp/lindera-example-training/source/rewrite.def
- /tmp/lindera-example-training/source/left-id.def
- /tmp/lindera-example-training/source/right-id.def
- /tmp/lindera-example-training/source/metadata.json
これ 名詞,代名詞,一般,*,*,*,これ,コレ,コレ
は 助詞,係助詞,*,*,*,*,は,ハ,ワ
外国 名詞,一般,*,*,*,*,外国,ガイコク,ガイコク
人 名詞,接尾,一般,*,*,*,人,ジン,ジン
参政 名詞,サ変接続,*,*,*,*,参政,サンセイ,サンセイ
権 名詞,接尾,一般,*,*,*,権,ケン,ケン
です 助動詞,*,*,*,特殊・デス,基本形,です,デス,デス
。 記号,句点,*,*,*,*,。,。,。
EOS