Chunking

The chunker segments the morphemes of a sentence into bunsetsu. It decides, for every morpheme, whether it starts a bunsetsu (B) or continues one (I), with a conditional random field over the two labels, as CaboCha does.

Chunking is in the default build and needs no other crate: the model is a table from feature string to the weights of B and I, with the weights of the transitions, and the labels are found by Viterbi. The table is read where it is in a model file. Training is behind the train feature.

Chunking a sentence

#![allow(unused)]
fn main() {
use lindera_dependency::lattice::{self, LatticeMorpheme};
use lindera_dependency::model::Model;
use lindera_dependency::{Bunsetsu, Morpheme, Sentence};

let model = Model::new(std::fs::read("chunker.model")?)?;
let chunker = model.chunker().expect("the file has a chunker");

// The morphemes of 彼は本を読んだ。 as IPADIC gives them. Any type that
// implements `Morpheme` will do.
let morphemes = vec![
    LatticeMorpheme::new("彼", "名詞,代名詞,一般,*,*,*,彼,カレ,カレ"),
    LatticeMorpheme::new("は", "助詞,係助詞,*,*,*,*,は,ハ,ワ"),
    LatticeMorpheme::new("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
    LatticeMorpheme::new("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ"),
    LatticeMorpheme::new("読ん", "動詞,自立,*,*,五段・マ行,連用タ接続,読む,ヨン,ヨン"),
    LatticeMorpheme::new("だ", "助動詞,*,*,*,特殊・タ,基本形,だ,ダ,ダ"),
    LatticeMorpheme::new("。", "記号,句点,*,*,*,*,。,。,。"),
];

// The ranges of the bunsetsu, as indices into the morphemes.
let ranges = chunker.chunk(&morphemes)?;
assert_eq!(ranges, [0..2, 2..4, 4..7]);
}

Chunker::chunk takes &self, and a chunker is Send + Sync, so one chunker serves several threads. The first morpheme always starts a bunsetsu, and an empty sentence has none.

A space (a morpheme whose surface is of white space alone, such as the full-width space a tokenizer gives as a token) is not given to the model: the bunsetsu are those of the sentence without its spaces. A space is then in the bunsetsu of the word after it, and the spaces at the end of the sentence are in the last bunsetsu. A sentence of spaces alone is one bunsetsu. Training leaves the spaces of its sentences out in the same way, and the features of the parser are those of a bunsetsu without its spaces.

The morphemes have to come from the dictionary the model was trained with, tokenized with the same settings: a model belongs to one dictionary. A morpheme with fewer feature columns than the schema of the model reads is refused with an error; see Checking the dictionary.

With the head word and the function word

A model file holds the schema of its dictionary, which gives the head word and the function word of each bunsetsu. The following writes the result in the lattice format. The heads are a placeholder here, every bunsetsu depending on the next one; the parser finds them.

#![allow(unused)]
fn main() {
let schema = model.schema();
let count = ranges.len();
let bunsetsu = ranges
    .into_iter()
    .enumerate()
    .map(|(index, range)| {
        let positions = schema.positions(&morphemes[range.clone()]);
        let mut bunsetsu = Bunsetsu::new(range, (index + 1 < count).then_some(index + 1));
        bunsetsu.positions = positions;
        bunsetsu
    })
    .collect();
let sentence = Sentence::new(morphemes, bunsetsu)?;
let mut output = Vec::new();
lattice::write(&mut output, &sentence)?;
print!("{}", String::from_utf8(output)?);
}
* 0 1D 0/1
彼	名詞,代名詞,一般,*,*,*,彼,カレ,カレ
は	助詞,係助詞,*,*,*,*,は,ハ,ワ
* 1 2D 0/1
本	名詞,一般,*,*,*,*,本,ホン,ホン
を	助詞,格助詞,一般,*,*,*,を,ヲ,ヲ
* 2 -1D 0/1
読ん	動詞,自立,*,*,五段・マ行,連用タ接続,読む,ヨン,ヨン
だ	助動詞,*,*,*,特殊・タ,基本形,だ,ダ,ダ
。	記号,句点,*,*,*,*,。,。,。
EOS

Training a model

The model for IPADIC that Lindera releases has a chunker, and so have the models for UniDic. To train one of your own from training data:

cargo run --release -p lindera-cli -- dependency train-chunker \
    --input train.lattice --output chunker.model

The model is for IPADIC unless --dictionary-name names another dictionary (unidic, unidic-cwj or unidic-csj): the name and the schema of that dictionary then go into the model, and the columns, the template and the coefficient are the ones for it.

On the train file of UD Japanese-GSD converted with IPADIC, this takes a few seconds and ends with:

train.lattice: 7024 sentences
iterations: 167
feature strings: 5408
weights: 10822
bytes: 309775

The output is a model file for the dictionary ipadic, with the chunker as its only part. Training the same data again gives the same bytes. The weights are f64. The format may change until the first release.

OptionDefaultMeaning
--regularizationl1l1 or l2
--lambda0.5The coefficient of the regularization
--columnssurface,pos,cformThe columns the template reads: surface, pos (the part of speech as its levels joined by -), ctype (conjugation type), cform (conjugation form), base (base form)
--templateThe template of CaboCha's chunker with five lines for a third columnA file in the format of CRF++
--max-iterations1000The largest number of iterations
--eta0.00005, the default of MeCab's learnerThe tolerance of the convergence test: the training stops before --max-iterations once the relative change of the objective stays below it for 3 iterations in a row. 0 turns the test off
--threadsThe number of CPUsThe number of threads
--sentences-onlyOffTrain on the sentences alone, without the texts made from them

chunk segments the morphemes of a file again with a model, for evaluate to compare with the answer:

cargo run --release -p lindera-cli -- dependency chunk \
    --model chunker.model --input dev.lattice --output output.lattice

It writes every bunsetsu as depending on the next one: it measures the chunker alone. parse --input-layer morphemes segments and parses.

A text of several sentences

A chunker is trained on sentences, and no sentence of its training data goes on after its period: in the train file of UD Japanese-GSD, 。 is the last morpheme of a sentence and nothing else. What a model does with the word after a 。 in the middle of a text is not learned, and it often starts no bunsetsu there (#1512): with the model of Lindera 7.1, 雨が降った。試合は中止になった。 is 雨が / 降った / 。試合は / 中止に / なった。, with the 。 in the bunsetsu of the word after it.

So Chunker::chunk cuts the words of a text into sentences, and gives each to the model on its own:

  • A sentence ends after a morpheme whose surface is of 。, !, ?, ! and ? alone, and after . unless a digit follows (lindera_dependency::morpheme::is_sentence_end). The half-width . ends none: UniDic gives it the part of speech of a period in 1.060 and in L.E.D..
  • The ends and the closing brackets that follow an end stay with it, and the word after them starts a sentence, and so a bunsetsu.
  • Two cases are not cut, where the word after the end belongs to the bunsetsu of a quotation: a function word of the schema after a closing bracket, as と in …要請している。」と言った。, and the particle of a quotation, と or って, also without a bracket, as in …同業者なのか?と、…. Another function word without a closing bracket starts a sentence as any word does (…なりました。だが、…).
  • A word of marks is read mark by mark. A dictionary can join marks into a word: IPADIC has no half-width symbol among its words, and gives 面白い(笑)。 as (, 笑 and )。, and 「本当?」 as 「, 本当 and ?」. Such a word ends a sentence when its last mark that is no closing bracket is a sentence end: ~。, )。, ?」 and (?) do, as their marks do when they are words of their own, and ,“ does not. The closing bracket of ?」 is a closing bracket for the case of the function word. A word with a letter or a digit is not read so: モーニング娘。 ends no sentence. Lindera 7.2.0 read a mark by its whole word, and cut after none of these.
  • A sentence end starts no bunsetsu. A sentence end, and an end or a closing bracket after it, is in the bunsetsu before it, whatever the model gives it, unless it is the first word of the text. A model takes a half-width mark that IPADIC gives as an unknown word for a noun: with Lindera 7.2.0, 行くの!? was 行くの / !?, and 「すごい!」と was 「すごい / !」と.

This holds inside brackets as outside. The token filter cuts a text at the sentence ends outside brackets for the parser too; a sentence inside a quotation is parsed with the sentence around it, and its bunsetsu are cut here.

Whether a chunker cuts is a setting of the schema of its model, Schema::sentence_split. Schema::ipadic() and Schema::unidic() cut (SentenceSplit::AfterEnds). A model converted from CaboCha's does not (SentenceSplit::None), as CaboCha gives its chunker the whole text, and neither does a model file of version 3 (Lindera 7.1). train-chunker cuts the sentences of its training data in the same places.

Each sentence of the dev and test files of UD Japanese-GSD and of UD Japanese-PUD joined to the next one, as it is and inside brackets followed by と言った。 (953 texts with IPADIC, 1,000 with UniDic), from their morphemes, before this rule and with it:

DictionaryTextsA bunsetsu starts after the period in the middle, beforeWith the ruleF of the bunsetsu, beforeWith the rule
IPADICJoined70.04%, 61.90%, 67.84%100%, 100%, 100%94.42, 93.84, 95.5997.07, 97.15, 98.05
IPADICQuoted70.04%, 61.90%, 67.84%100%, 100%, 100%94.78, 94.11, 95.7997.27, 97.24, 98.13
UniDicJoined30.56%, 35.83%, 36.03%100%, 100%, 100%90.65, 91.18, 93.0897.09, 97.06, 98.03
UniDicQuoted30.56%, 35.83%, 36.03%100%, 100%, 100%91.13, 91.54, 93.4097.19, 97.13, 98.11

The weights of a model are the same with and without the rule. On the files of the corpus as they are, no sentence of the train file changes, and one sentence of the dev file and one of PUD do, both to the bunsetsu of the answer. Training with joined sentences was tried in place of a rule: it also cuts before と in …。」と言った。, and the F of the quoted texts falls to 89 to 91. An exception for every particle was tried too: a sentence that starts with でも or にもかかわらず is then not cut off, as UniDic gives these as particles.

Texts that do not end as a sentence

The sentences of a corpus end with a period, so a chunker trained on them alone learns the end of a text from periods only, and it cuts the last bunsetsu of a title, of a noun phrase or of a query wrongly (#1499): 人を噛んだ犬 became 人を / 噛んだ犬, where it is 人を / 噛んだ / 犬. train-chunker therefore makes two more texts from each sentence of its input, and trains on them too:

  • the sentence without its last period;
  • a phrase: the sentence up to the first bunsetsu, from the second one to the one before the last, that ends with particles after another word, without those particles (人を噛んだ犬 from 人を噛んだ犬が…).

Each is a start of the sentence, with the bunsetsu the sentence has there. --sentences-only trains on the sentences alone; in the library, the setting is TrainOptions::unfinished_texts. The parser is trained on the sentences as they are.

How often the last bunsetsu of a text starts where it should, for texts made in the same two ways from files the chunker was not trained on, from their morphemes:

DictionaryTextsTrainingGSD devGSD testPUD
IPADICSentences without their periodSentences alone86.71% (424 / 489)83.33% (415 / 498)93.58% (918 / 981)
IPADICSentences without their periodWith the texts98.16% (480 / 489)96.79% (482 / 498)98.47% (966 / 981)
IPADICPhrasesSentences alone69.69% (315 / 452)65.83% (314 / 477)75.82% (743 / 980)
IPADICPhrasesWith the texts97.12% (439 / 452)97.27% (464 / 477)99.18% (972 / 980)
UniDicSentences without their periodSentences alone97.42% (491 / 504)95.42% (500 / 524)98.49% (976 / 991)
UniDicSentences without their periodWith the texts98.21% (495 / 504)96.95% (508 / 524)98.49% (976 / 991)
UniDicPhrasesSentences alone90.73% (411 / 453)90.27% (427 / 473)94.27% (922 / 978)
UniDicPhrasesWith the texts96.25% (436 / 453)97.25% (460 / 473)99.18% (970 / 978)

On the files as they are, the two trainings do not differ: the F of the chunking is 96.93, 96.89 and 98.03 with the texts against 96.85, 96.92 and 98.04 for IPADIC, and 97.07, 97.11 and 98.03 against 97.03, 97.24 and 98.00 for UniDic (McNemar's test on the sentences segmented right: p = 0.17 or more in the six cases). The chunker for IPADIC grows from 261,858 to 309,774 bytes. Phrases that end with a noun only measured the same, and need the name a dictionary gives its nouns.

Accuracy

With the defaults, trained on the train file of UD Japanese-GSD (commit c662dc9) with IPADIC:

FPrecisionRecallSentences with every bunsetsu right
UD Japanese-GSD dev96.9797.12% (4,015 / 4,134)96.82% (4,015 / 4,147)436 / 506
UD Japanese-GSD test97.0297.01% (4,375 / 4,510)97.03% (4,375 / 4,509)460 / 542
UD Japanese-PUD98.0498.07% (9,648 / 9,838)98.02% (9,648 / 9,843)883 / 994

The defaults were chosen by a 10-fold cross-validation on the train file. The conjugation form helps, the conjugation type does not, and L1 is better than L2 with a model about fifty times smaller. The tables of the cross-validation are in the README of the crate, and scripts/dependency runs them again.

With UniDic

The numbers of the two tables of this section are those of the experiments as they were run, with the chunker and the schema of Lindera 7.1: before the head word of a bunsetsu without one changed (#1507) and before the chunker was trained with texts that do not end as a sentence (#1499). They were not run again; the models of 7.2 do not differ from those of 7.1 on these files (McNemar's test, p = 0.09 or more for the four dictionaries).

train-chunker --dictionary-name unidic (or unidic-cwj, unidic-csj) trains with other settings than for IPADIC: four columns, the surface, the part of speech, the conjugation form and the base form, with Template::unidic(), and L1 regularization with the coefficient 0.25. TrainOptions::for_dictionary gives the settings of a dictionary. As for IPADIC, an option of the command replaces any of them.

The settings were chosen again by the cross-validation on the train file, with UniDic CWJ, and hold with the two other dictionaries. The base form of UniDic is the lexeme (語彙素), which is the same for the ways a word is written; it helps here, and it did not with IPADIC. F over the 10 folds, the sentences only one of the two settings segments right, and McNemar's test:

DictionaryThe settings for IPADICThe settings for UniDicFirst only / second onlyp
unidic97.0297.1575 / 1220.0010
unidic-cwj97.0297.2259 / 131< 0.0001
unidic-csj96.9497.0874 / 1310.0001

On the files that are not trained on, the two settings cannot be told apart: the files are small (506, 542 and 994 sentences). F with the settings for IPADIC and with those for UniDic:

DictionaryUD Japanese-GSD devUD Japanese-GSD testUD Japanese-PUD
unidic96.89 and 97.03 (p 0.09)97.08 and 97.24 (p 0.82)98.02 and 98.00 (p 1.00)
unidic-cwj96.63 and 96.63 (p 1.00)96.85 and 97.02 (p 0.50)97.96 and 97.89 (p 0.70)
unidic-csj96.60 and 96.60 (p 0.69)96.79 and 96.95 (p 0.48)97.94 and 97.78 (p 0.34)

UD Japanese-PUD is lower with the settings for UniDic, by a difference that is not significant. The settings are the ones the cross-validation chose, as for IPADIC; the tables of the cross-validation are in the README of the crate.

How the features are made

The feature strings are made in two steps that can each be replaced:

  1. Columns. For each morpheme, the columns of the model are read through the schema: the surface, the part of speech, the conjugation form.
  2. Template. A template in the format of CRF++ expands the columns of the morpheme and of its neighbours into feature strings: U02:%x[0,0] is the first column of the morpheme itself, U11:%x[-1,1] the second column of the one before. A position outside the sentence gives _B-1, _B+1 and so on.

The decoder sees only the feature strings and the table of weights. Chunker::features makes the strings and Chunker::labels decodes them, so an extractor of your own can feed the same decoder.