use std::collections::HashMap;
use std::num::NonZeroU32;
use lindera_crf::{Edge, FeatureProvider, FeatureSet, Lattice, RawModel, StopReason, Trainer};
use super::columns::Column;
use super::extract;
use super::model::{ChunkerModel, Label};
use super::template::Template;
use crate::error::{Error, Result};
use crate::morpheme::Morpheme;
use crate::schema::Schema;
use crate::sentence::Sentence;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Regularization {
L1,
L2,
}
#[derive(Debug, Clone, PartialEq)]
pub struct TrainOptions {
pub schema: Schema,
pub columns: Vec<Column>,
pub template: Template,
pub regularization: Regularization,
pub lambda: f64,
pub max_iterations: u64,
pub threads: usize,
}
impl Default for TrainOptions {
fn default() -> Self {
Self {
schema: Schema::ipadic(),
columns: vec![
Column::Surface,
Column::PartOfSpeech,
Column::ConjugationForm,
],
template: Template::default(),
regularization: Regularization::L1,
lambda: 0.5,
max_iterations: 1000,
threads: 1,
}
}
}
impl TrainOptions {
pub fn for_dictionary(dictionary: &str) -> Option<Self> {
let schema = Schema::for_dictionary(dictionary)?;
if dictionary == "ipadic" {
return Some(Self {
schema,
..Self::default()
});
}
Some(Self {
schema,
columns: vec![
Column::Surface,
Column::PartOfSpeech,
Column::ConjugationForm,
Column::BaseForm,
],
template: Template::unidic(),
lambda: 0.25,
..Self::default()
})
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Trained {
pub model: ChunkerModel,
pub iterations: u64,
pub converged: bool,
}
fn feature_id(string: u32, label: Label) -> Option<NonZeroU32> {
string
.checked_mul(2)?
.checked_add(1 + label.index() as u32)
.and_then(NonZeroU32::new)
}
fn bigram_id(label: Label) -> Option<NonZeroU32> {
NonZeroU32::new(label.index() as u32 + 1)
}
fn crf_error(error: lindera_crf::errors::RucrfError) -> Error {
Error::Chunker(format!("training failed: {error}"))
}
fn add_edge(
lattice: &mut Lattice,
provider: &mut FeatureProvider,
position: usize,
label: Label,
strings: &[u32],
) -> Result<NonZeroU32> {
let too_many = || Error::Chunker("too many feature strings".to_string());
let unigram = strings
.iter()
.map(|&string| feature_id(string, label).ok_or_else(too_many))
.collect::<Result<Vec<NonZeroU32>>>()?;
let bigram = [bigram_id(label)];
let edge_label = provider
.add_feature_set(FeatureSet::new(&unigram, &bigram, &bigram))
.map_err(crf_error)?;
lattice
.add_edge(position, Edge::new(position + 1, edge_label))
.map_err(crf_error)?;
Ok(edge_label)
}
struct Raw {
model: RawModel,
strings: HashMap<String, u32>,
iterations: u64,
converged: bool,
}
fn train_raw<M: Morpheme>(sentences: &[Sentence<M>], options: &TrainOptions) -> Result<Raw> {
if options.template.columns() > options.columns.len() {
return Err(Error::Chunker(format!(
"the template reads {} columns, and {} are given",
options.template.columns(),
options.columns.len()
)));
}
let mut strings: HashMap<String, u32> = HashMap::new();
let mut provider = FeatureProvider::new();
let mut lattices = Vec::new();
for (index, sentence) in sentences.iter().enumerate() {
sentence.check()?;
if sentence.morphemes.is_empty() {
continue;
}
if sentence.bunsetsu.is_empty() {
return Err(Error::Chunker(format!(
"sentence {} of the training data has no bunsetsu",
index + 1
)));
}
let mut gold = vec![Label::Inside; sentence.morphemes.len()];
for bunsetsu in &sentence.bunsetsu {
gold[bunsetsu.morphemes.start] = Label::Begin;
}
let features = extract(
&options.schema,
&options.columns,
&options.template,
&sentence.morphemes,
);
let mut lattice = Lattice::new(features.len()).map_err(crf_error)?;
for (position, features) in features.into_iter().enumerate() {
let ids: Vec<u32> = features
.into_iter()
.map(|feature| {
let next = strings.len() as u32;
*strings.entry(feature).or_insert(next)
})
.collect();
add_edge(&mut lattice, &mut provider, position, gold[position], &ids)?;
if position > 0 {
let other = match gold[position] {
Label::Begin => Label::Inside,
Label::Inside => Label::Begin,
};
add_edge(&mut lattice, &mut provider, position, other, &ids)?;
}
}
lattices.push(lattice);
}
if lattices.is_empty() {
return Err(Error::Chunker(
"the training data has no sentence".to_string(),
));
}
let regularization = match options.regularization {
Regularization::L1 => lindera_crf::Regularization::L1,
Regularization::L2 => lindera_crf::Regularization::L2,
};
let trainer = Trainer::new()
.regularization(regularization, options.lambda)
.map_err(crf_error)?
.max_iter(options.max_iterations)
.map_err(crf_error)?
.n_threads(options.threads)
.map_err(crf_error)?;
let (model, stats) = trainer.train_with_stats(&lattices, provider);
Ok(Raw {
model,
strings,
iterations: stats.iterations,
converged: stats.stop_reason == StopReason::Converged,
})
}
fn chunker_model(raw: &Raw, options: &TrainOptions) -> Result<ChunkerModel> {
let mut features = HashMap::new();
for (feature, &string) in &raw.strings {
let mut weights = [0.0; 2];
for label in Label::ALL {
if let Some(id) = feature_id(string, label) {
weights[label.index()] = raw.model.unigram_weight(&[id]);
}
}
if weights != [0.0; 2] {
features.insert(feature.clone(), weights);
}
}
let mut transitions = [[0.0; 3]; 3];
let indices = raw.model.bigram_weight_indices();
for (from, row) in transitions.iter_mut().enumerate() {
for (to, weight) in row.iter_mut().enumerate() {
if let Some(&index) = indices.get(from).and_then(|map| map.get(&(to as u32))) {
*weight = raw.model.weights()[index as usize];
}
}
}
ChunkerModel::new(
options.schema.clone(),
options.columns.clone(),
options.template.clone(),
transitions,
features,
)
}
pub fn train<M: Morpheme>(sentences: &[Sentence<M>], options: &TrainOptions) -> Result<Trained> {
let raw = train_raw(sentences, options)?;
Ok(Trained {
model: chunker_model(&raw, options)?,
iterations: raw.iterations,
converged: raw.converged,
})
}
#[cfg(test)]
mod tests {
use lindera_crf::Model;
use super::*;
use crate::chunker::Chunker;
use crate::lattice::{self, LatticeMorpheme};
use crate::model::{Model as ModelFile, ModelBuilder};
fn crf_labels(raw: &mut Raw, features: &[Vec<String>]) -> Vec<Label> {
let mut lattice = Lattice::new(features.len()).unwrap();
let mut labels = HashMap::new();
for (position, features) in features.iter().enumerate() {
let ids: Vec<u32> = features
.iter()
.filter_map(|feature| raw.strings.get(feature).copied())
.collect();
for label in Label::ALL {
if position == 0 && label == Label::Inside {
continue;
}
let edge_label = add_edge(
&mut lattice,
raw.model.feature_provider(),
position,
label,
&ids,
)
.unwrap();
labels.insert(edge_label, label);
}
}
let (path, _) = raw.model.search_best_path(&lattice);
path.iter().map(|edge| labels[&edge.label()]).collect()
}
fn gold_labels<M>(sentence: &Sentence<M>) -> Vec<Label> {
let mut labels = vec![Label::Inside; sentence.morphemes.len()];
for bunsetsu in &sentence.bunsetsu {
labels[bunsetsu.morphemes.start] = Label::Begin;
}
labels
}
fn same_labels(
raw: &mut Raw,
options: &TrainOptions,
sentences: &[Sentence<LatticeMorpheme>],
) -> usize {
let chunker = Chunker::new(chunker_model(raw, options).unwrap());
let mut right = 0;
for (index, sentence) in sentences.iter().enumerate() {
if sentence.morphemes.is_empty() {
continue;
}
let features = chunker.features(&sentence.morphemes);
let labels = chunker.labels(&features);
assert_eq!(labels, crf_labels(raw, &features), "sentence {}", index + 1);
if labels == gold_labels(sentence) {
right += 1;
}
}
right
}
fn sentence(bunsetsu: &[&[&str]]) -> String {
let mut text = String::new();
for (index, morphemes) in bunsetsu.iter().enumerate() {
let head = if index + 1 == bunsetsu.len() {
-1
} else {
index as i32 + 1
};
text.push_str(&format!("* {index} {head}D \n"));
for morpheme in *morphemes {
let (surface, pos) = morpheme.split_once('/').unwrap();
text.push_str(&format!("{surface}\t{pos},*,*,*,*,*,{surface},*,*\n"));
}
}
text.push_str("EOS\n");
text
}
fn training_data() -> Vec<Sentence<LatticeMorpheme>> {
let text = [
sentence(&[
&["彼/名詞", "は/助詞"],
&["本/名詞", "を/助詞"],
&["読む/動詞"],
]),
sentence(&[
&["私/名詞", "が/助詞"],
&["水/名詞", "を/助詞"],
&["飲む/動詞"],
]),
sentence(&[&["犬/名詞", "が/助詞"], &["走る/動詞"]]),
sentence(&[
&["猫/名詞", "は/助詞"],
&["魚/名詞", "を/助詞"],
&["食べる/動詞"],
]),
sentence(&[&["本/名詞", "を/助詞"], &["読む/動詞"]]),
sentence(&[&["東京/名詞", "都/名詞", "に/助詞"], &["行く/動詞"]]),
sentence(&[
&["彼/名詞", "は/助詞"],
&["日本/名詞", "語/名詞", "を/助詞"],
&["話す/動詞"],
]),
sentence(&[
&["x/記号", "x/記号"],
&["x/記号", "x/記号"],
&["x/記号", "x/記号"],
]),
sentence(&[
&["x/記号", "x/記号"],
&["x/記号", "x/記号"],
&["x/記号", "x/記号"],
&["x/記号", "x/記号"],
]),
]
.concat();
lattice::parse(&text).unwrap()
}
fn other_data() -> Vec<Sentence<LatticeMorpheme>> {
let text = [
sentence(&[
&["犬/名詞", "は/助詞"],
&["水/名詞", "を/助詞"],
&["飲む/動詞"],
]),
sentence(&[&["鳥/名詞", "が/助詞"], &["飛ぶ/動詞"]]),
sentence(&[&["読む/動詞"]]),
sentence(&[&["は/助詞"], &["を/助詞", "が/助詞"]]),
sentence(&[
&["x/記号", "x/記号"],
&["x/記号", "x/記号"],
&["x/記号", "x/記号"],
&["x/記号", "x/記号"],
&["x/記号", "x/記号"],
]),
sentence(&[&["未知/感動詞", "語/感動詞"], &["x/記号"]]),
]
.concat();
lattice::parse(&text).unwrap()
}
fn options(regularization: Regularization, lambda: f64) -> TrainOptions {
TrainOptions {
regularization,
lambda,
..TrainOptions::default()
}
}
#[test]
fn the_chunker_gives_the_labels_of_search_best_path() {
for (regularization, lambda) in [
(Regularization::L2, 0.01),
(Regularization::L2, 1.0),
(Regularization::L1, 0.01),
(Regularization::L1, 0.5),
] {
let options = options(regularization, lambda);
let training = training_data();
let mut raw = train_raw(&training, &options).unwrap();
let right = same_labels(&mut raw, &options, &training);
if lambda == 0.01 {
assert_eq!(right, training.len(), "{regularization:?} {lambda}");
}
same_labels(&mut raw, &options, &other_data());
}
}
#[test]
fn the_transitions_between_labels_are_learned() {
let options = options(Regularization::L2, 0.01);
let trained = train(&training_data(), &options).unwrap();
let chunker = Chunker::new(trained.model);
let run: Vec<LatticeMorpheme> = (0..10)
.map(|_| LatticeMorpheme::new("x", "記号,*,*,*,*,*,x,*,*"))
.collect();
assert_eq!(
chunker.chunk(&run).unwrap(),
[0..2, 2..4, 4..6, 6..8, 8..10]
);
let model = chunker.model();
assert!(model.transition(1, 2) > model.transition(1, 1));
assert!(model.transition(2, 1) > model.transition(2, 2));
assert_eq!(model.transition(0, 2), 0.0);
assert_ne!(model.transition(2, 0), 0.0);
}
#[test]
fn a_trained_model_chunks_and_goes_through_bytes() {
let options = options(Regularization::L2, 0.01);
let trained = train(&training_data(), &options).unwrap();
assert!(trained.iterations > 0);
let model = trained.model;
assert_eq!(model.schema(), &options.schema);
assert_eq!(model.columns(), options.columns);
assert_eq!(model.template(), &options.template);
let bytes = ModelBuilder::new("test", options.schema.clone())
.unwrap()
.chunker(&model)
.unwrap()
.to_bytes();
let read = ModelFile::new(bytes).unwrap();
let chunker = read.chunker().unwrap();
assert_eq!(chunker.model().feature_count(), model.feature_count());
assert_eq!(chunker.model().weight_count(), model.weight_count());
for sentence in training_data() {
let expected: Vec<_> = sentence
.bunsetsu
.iter()
.map(|bunsetsu| bunsetsu.morphemes.clone())
.collect();
assert_eq!(chunker.chunk(&sentence.morphemes).unwrap(), expected);
}
}
#[test]
fn the_settings_of_a_dictionary_are_those_of_its_model() {
assert_eq!(
TrainOptions::for_dictionary("ipadic"),
Some(TrainOptions::default())
);
for name in ["unidic", "unidic-cwj", "unidic-csj"] {
let options = TrainOptions::for_dictionary(name).unwrap();
assert_eq!(options.schema, Schema::unidic(), "{name}");
assert_eq!(
options.columns,
[
Column::Surface,
Column::PartOfSpeech,
Column::ConjugationForm,
Column::BaseForm
],
"{name}"
);
assert_eq!(options.template, Template::unidic(), "{name}");
assert_eq!(options.regularization, Regularization::L1, "{name}");
assert_eq!(options.lambda, 0.25, "{name}");
assert_eq!(options.template.columns(), options.columns.len());
}
for name in Schema::DICTIONARIES {
assert!(TrainOptions::for_dictionary(name).is_some(), "{name}");
}
assert_eq!(TrainOptions::for_dictionary("ko-dic"), None);
}
#[test]
fn l1_leaves_fewer_weights_than_l2() {
let training = training_data();
let l2 = train(&training, &options(Regularization::L2, 0.1))
.unwrap()
.model;
let l1 = train(&training, &options(Regularization::L1, 0.1))
.unwrap()
.model;
assert!(
l1.feature_count() < l2.feature_count(),
"{} and {}",
l1.feature_count(),
l2.feature_count()
);
assert!(l1.weight_count() < l2.weight_count());
assert!(l1.weight_count() >= l1.feature_count());
}
#[test]
fn refuses_training_data_and_settings_it_cannot_use() {
let error = |sentences: &[Sentence<LatticeMorpheme>], options: &TrainOptions| {
train(sentences, options).unwrap_err().to_string()
};
let training = training_data();
let default = TrainOptions::default();
assert_eq!(error(&[], &default), "the training data has no sentence");
let morphemes_only = lattice::parse("彼\t名詞\nEOS\n").unwrap();
assert_eq!(
error(&morphemes_only, &default),
"sentence 1 of the training data has no bunsetsu"
);
let one_column = TrainOptions {
columns: vec![Column::Surface],
..TrainOptions::default()
};
assert_eq!(
error(&training, &one_column),
"the template reads 3 columns, and 1 are given"
);
for options in [
TrainOptions {
lambda: -1.0,
..TrainOptions::default()
},
TrainOptions {
max_iterations: 0,
..TrainOptions::default()
},
TrainOptions {
threads: 0,
..TrainOptions::default()
},
] {
let message = error(&training, &options);
assert!(message.starts_with("training failed: "), "{message}");
}
}
#[test]
#[ignore = "needs training data: see the comment"]
fn the_chunker_gives_the_labels_of_search_best_path_on_real_data() {
let read = |path: &str| {
let text = std::fs::read_to_string(path).unwrap();
lattice::parse(&text).unwrap()
};
let training = read(&std::env::var("LINDERA_DEPENDENCY_CHUNKER_TRAIN").unwrap());
let files = std::env::var("LINDERA_DEPENDENCY_CHUNKER_EVAL").unwrap();
let threads = std::thread::available_parallelism().map_or(1, usize::from);
for (regularization, lambda) in [(Regularization::L1, 1.0), (Regularization::L2, 1.0)] {
let options = TrainOptions {
regularization,
lambda,
threads,
..TrainOptions::default()
};
let mut raw = train_raw(&training, &options).unwrap();
for path in files.split(':') {
let sentences = read(path);
let right = same_labels(&mut raw, &options, &sentences);
println!(
"{regularization:?} {lambda} {path}: {} sentences with the same labels, {right} as the answer",
sentences.len()
);
}
}
}
}