1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
use std::collections::BTreeMap;
use anyhow::{anyhow, Result};
use fst::raw::Fst;
use crate::feature::{ExampleGenerator, FeatureExtractor};
use crate::model::Model;
use crate::sentence::Sentence;
use crate::utils::FeatureIDManager;
#[cfg_attr(docsrs, doc(cfg(feature = "train")))]
pub struct Dataset<'a> {
dictionary_fst: Fst<Vec<u8>>,
feature_extractor: FeatureExtractor,
example_generator: ExampleGenerator,
char_window_size: usize,
type_window_size: usize,
dict_word_max_size: usize,
fid_manager: FeatureIDManager<'a>,
xs: Vec<Vec<(u32, f64)>>,
ys: Vec<f64>,
}
impl<'a> Dataset<'a> {
pub fn new<D, P>(
char_ngram_size: usize,
char_window_size: usize,
type_ngram_size: usize,
type_window_size: usize,
dictionary: D,
dict_word_max_size: usize,
) -> Result<Self>
where
D: AsRef<[P]>,
P: AsRef<[u8]> + AsRef<str>,
{
Ok(Self {
dictionary_fst: Fst::from_iter_map(
dictionary
.as_ref()
.iter()
.enumerate()
.map(|(i, word)| (word, i as u64)),
)?,
feature_extractor: FeatureExtractor::new(
char_ngram_size,
type_ngram_size,
dictionary,
dict_word_max_size,
)?,
example_generator: ExampleGenerator::new(char_window_size, type_window_size),
char_window_size,
type_window_size,
dict_word_max_size,
fid_manager: FeatureIDManager::default(),
xs: vec![],
ys: vec![],
})
}
pub fn push_sentence(&mut self, s: &'a Sentence) {
let feature_spans = self.feature_extractor.extract(s);
let examples = self.example_generator.generate(s, feature_spans, false);
for example in examples {
let mut feature_ids = BTreeMap::new();
for f in example.features {
let fid = self.fid_manager.get_id(f) + 1;
if let Some(v) = feature_ids.get_mut(&fid) {
*v += 1.0;
} else {
feature_ids.insert(fid, 1.0);
}
}
self.xs.push(feature_ids.into_iter().collect());
self.ys.push(example.label as u8 as f64);
}
}
pub fn n_features(&self) -> usize {
self.fid_manager.map.len()
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "train")))]
pub struct Trainer {
epsilon: f64,
cost: f64,
bias: f64,
}
impl Trainer {
pub const fn new(epsilon: f64, cost: f64, bias: f64) -> Self {
Self {
epsilon,
cost,
bias,
}
}
pub fn train(&self, dataset: Dataset) -> Result<Model> {
let mut builder = liblinear::Builder::new();
let training_input =
liblinear::util::TrainingInput::from_sparse_features(dataset.ys, dataset.xs)
.map_err(|e| anyhow!("liblinear error: {:?}", e))?;
builder.problem().input_data(training_input).bias(self.bias);
builder
.parameters()
.solver_type(liblinear::SolverType::L1R_L2LOSS_SVC)
.stopping_criterion(self.epsilon)
.constraints_violation_cost(self.cost);
let model = builder.build_model().map_err(|e| anyhow!(e.to_string()))?;
Ok(Model::from_liblinear_model(
model,
dataset.fid_manager,
dataset.dictionary_fst,
dataset.char_window_size,
dataset.type_window_size,
dataset.dict_word_max_size,
))
}
}