use std::collections::HashMap;
use std::num::NonZeroU32;
use lindera_crf::{Edge, FeatureProvider, FeatureSet, Lattice, RawModel, StopReason, Trainer};
use super::columns::Column;
use super::model::{ChunkerModel, Label};
use super::template::Template;
use super::{extract, words};
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,
pub unfinished_texts: bool,
}
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,
unfinished_texts: true,
}
}
}
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 unfinished_ends<M: Morpheme>(schema: &Schema, words: &[M], labels: &[Label]) -> Vec<usize> {
let mut ends = Vec::new();
if words.len() > 1 && schema.is_period(&words[words.len() - 1]) {
ends.push(words.len() - 1);
}
let starts: Vec<usize> = (0..labels.len())
.filter(|&index| index == 0 || labels[index] == Label::Begin)
.collect();
for number in 1..starts.len().saturating_sub(1) {
let bunsetsu = &words[starts[number]..starts[number + 1]];
let mut end = bunsetsu.len();
while end > 0 && schema.is_particle(bunsetsu, end - 1) {
end -= 1;
}
if end == 0 || end == bunsetsu.len() {
continue;
}
ends.push(starts[number] + end);
break;
}
ends
}
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 starts = vec![false; sentence.morphemes.len()];
for bunsetsu in &sentence.bunsetsu {
starts[bunsetsu.morphemes.start] = true;
}
let words = words(&sentence.morphemes);
if words.is_empty() {
continue;
}
let mut gold = Vec::with_capacity(words.len());
let mut next = 0;
for &word in &words {
gold.push(if starts[next..=word].contains(&true) {
Label::Begin
} else {
Label::Inside
});
next = word + 1;
}
let kept: Vec<&M> = words
.iter()
.map(|&index| &sentence.morphemes[index])
.collect();
let mut from = 0;
for to in options
.schema
.sentence_starts(&kept)
.into_iter()
.chain([kept.len()])
{
let kept = &kept[from..to];
let mut gold = gold[from..to].to_vec();
gold[0] = Label::Begin;
from = to;
let mut ends = vec![kept.len()];
if options.unfinished_texts {
ends.extend(unfinished_ends(&options.schema, kept, &gold));
}
for end in ends {
let features = extract(
&options.schema,
&options.columns,
&options.template,
&kept[..end],
);
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()
);
}
}
}
#[test]
fn the_spaces_of_the_training_data_are_not_read() {
let plain = sentence(&[
&["彼/名詞", "は/助詞"],
&["本/名詞", "を/助詞"],
&["読む/動詞"],
]);
let spaced = sentence(&[
&["\u{3000}/記号", "彼/名詞", "は/助詞"],
&["\u{3000}/記号", "本/名詞", "\u{3000}/記号", "を/助詞"],
&["読む/動詞", "\u{3000}/記号"],
]);
let options = options(Regularization::L2, 0.01);
let mut without = training_data();
without.extend(lattice::parse(&plain).unwrap());
let mut with = training_data();
with.extend(lattice::parse(&spaced).unwrap());
assert_ne!(with, without);
let with = train(&with, &options).unwrap();
let without = train(&without, &options).unwrap();
assert_eq!(with.model, without.model);
assert_eq!(with.iterations, without.iterations);
let bytes = ModelFile::new(
ModelBuilder::new("ipadic", options.schema.clone())
.unwrap()
.chunker(&with.model)
.unwrap()
.to_bytes(),
)
.unwrap();
assert!(!String::from_utf8_lossy(bytes.as_bytes()).contains('\u{3000}'));
let spaces = lattice::parse(&sentence(&[&["\u{3000}/記号", "\u{3000}/記号"]])).unwrap();
let mut with_spaces = training_data();
with_spaces.extend(spaces.clone());
assert_eq!(
train(&with_spaces, &options).unwrap().model,
train(&training_data(), &options).unwrap().model
);
assert_eq!(
train(&spaces, &options).unwrap_err().to_string(),
"the training data has no sentence"
);
}
fn ends(bunsetsu: &[&[&str]]) -> Vec<usize> {
let sentences = lattice::parse(&sentence(bunsetsu)).unwrap();
let one = &sentences[0];
let labels = gold_labels(one);
unfinished_ends(&Schema::ipadic(), &one.morphemes, &labels)
}
#[test]
fn the_texts_made_from_a_sentence_end_before_its_period_and_after_a_phrase() {
assert_eq!(
ends(&[
&["彼/名詞", "は/助詞"],
&["本/名詞", "を/助詞"],
&["読む/動詞", "。/記号,句点"],
]),
[5, 3]
);
assert_eq!(
ends(&[
&["彼/名詞", "は/助詞"],
&["赤い/形容詞"],
&["は/助詞"],
&["走っ/動詞", "て/助詞", "も/助詞"],
&["本/名詞", "を/助詞"],
&["読む/動詞", "。/記号,句点"],
]),
[10, 5]
);
assert_eq!(
ends(&[&["犬/名詞", "が/助詞"], &["走る/動詞", "。/記号,句点"]]),
[3]
);
assert_eq!(
ends(&[
&["彼/名詞", "は/助詞"],
&["本/名詞", "を/助詞"],
&["読む/動詞", "と/助詞"],
]),
[3]
);
assert!(ends(&[&["犬/名詞", "が/助詞"], &["走る/動詞"]]).is_empty());
assert!(ends(&[&["彼/名詞", "は/助詞"], &["赤い/形容詞"], &["本/名詞"]]).is_empty());
assert!(ends(&[&["。/記号,句点"]]).is_empty());
}
#[test]
fn the_training_adds_the_texts_made_from_the_sentences() {
let full: &[&[&str]] = &[
&["彼/名詞", "は/助詞"],
&["本/名詞", "を/助詞"],
&["読む/動詞", "。/記号,句点"],
];
let data = |texts: &[&[&[&str]]]| {
let mut sentences = training_data();
for text in texts {
sentences.extend(lattice::parse(&sentence(text)).unwrap());
}
sentences
};
let written_out = {
let mut sentences = Vec::new();
for one in data(&[full]) {
let labels = gold_labels(&one);
let ends = unfinished_ends(&Schema::ipadic(), &one.morphemes, &labels);
let starts: Vec<usize> = one
.bunsetsu
.iter()
.map(|bunsetsu| bunsetsu.morphemes.start)
.collect();
sentences.push(one.clone());
for end in ends {
let mut text = String::new();
let mut number = 0;
for (index, morpheme) in one.morphemes[..end].iter().enumerate() {
if starts.contains(&index) {
text.push_str(&format!("* {number} -1D \n"));
number += 1;
}
text.push_str(&format!(
"{}\t{}\n",
morpheme.surface(),
morpheme.features()
));
}
text.push_str("EOS\n");
sentences.extend(lattice::parse(&text).unwrap());
}
}
sentences
};
assert!(written_out.len() >= data(&[full]).len() + 2);
let with = TrainOptions {
unfinished_texts: true,
..options(Regularization::L2, 0.01)
};
let without = TrainOptions {
unfinished_texts: false,
..with.clone()
};
assert!(TrainOptions::default().unfinished_texts);
let trained = train(&data(&[full]), &with).unwrap();
assert_eq!(trained.model, train(&written_out, &without).unwrap().model);
assert_ne!(
trained.model,
train(&data(&[full]), &without).unwrap().model
);
}
#[test]
fn a_chunker_trained_with_the_texts_cuts_a_text_without_a_period() {
let mut text = String::new();
for (subject, object, verb) in [
("彼", "本", "読む"),
("私", "水", "飲む"),
("犬", "魚", "食べる"),
("猫", "道", "歩く"),
] {
text.push_str(&sentence(&[
&[&format!("{subject}/名詞"), "は/助詞"],
&[&format!("{object}/名詞"), "を/助詞"],
&[&format!("{verb}/動詞"), "。/記号,句点"],
]));
}
let sentences = lattice::parse(&text).unwrap();
let with = options(Regularization::L2, 0.01);
let without = TrainOptions {
unfinished_texts: false,
..with.clone()
};
let unfinished = lattice::parse(&sentence(&[
&["彼/名詞", "は/助詞"],
&["本/名詞", "を/助詞"],
&["読む/動詞"],
]))
.unwrap();
let morphemes = &unfinished[0].morphemes;
let chunk = |options: &TrainOptions| {
Chunker::new(train(&sentences, options).unwrap().model)
.chunk(morphemes)
.unwrap()
};
assert_eq!(chunk(&with), [0..2, 2..4, 4..5]);
for options in [&with, &without] {
let chunker = Chunker::new(train(&sentences, options).unwrap().model);
for one in &sentences {
assert_eq!(
chunker.chunk(&one.morphemes).unwrap(),
one.bunsetsu
.iter()
.map(|bunsetsu| bunsetsu.morphemes.clone())
.collect::<Vec<_>>()
);
}
}
}
#[test]
fn a_text_of_several_sentences_is_trained_on_as_its_sentences() {
let first: &[&[&str]] = &[
&["彼/名詞", "は/助詞"],
&["本/名詞", "を/助詞"],
&["読む/動詞", "。/記号,句点"],
];
let second: &[&[&str]] = &[&["犬/名詞", "が/助詞"], &["走る/動詞", "。/記号,句点"]];
let joined: &[&[&str]] = &[
&["彼/名詞", "は/助詞"],
&["本/名詞", "を/助詞"],
&["読む/動詞", "。/記号,句点", "犬/名詞", "が/助詞"],
&["走る/動詞", "。/記号,句点"],
];
let data = |texts: &[&[&[&str]]]| {
let mut sentences = training_data();
for text in texts {
sentences.extend(lattice::parse(&sentence(text)).unwrap());
}
sentences
};
let options = options(Regularization::L2, 0.01);
assert_eq!(
options.schema.sentence_split,
crate::schema::SentenceSplit::AfterEnds
);
let apart = train(&data(&[first, second]), &options).unwrap();
let together = train(&data(&[joined]), &options).unwrap();
assert_eq!(together.model, apart.model);
let whole = TrainOptions {
schema: Schema {
sentence_split: crate::schema::SentenceSplit::None,
..options.schema.clone()
},
..options.clone()
};
let uncut = train(&data(&[joined]), &whole).unwrap();
let uncut_apart = train(&data(&[first, second]), &whole).unwrap();
assert_ne!(uncut.model, uncut_apart.model);
}
}