lindera_dependency/parser/
classifier.rs1use std::collections::HashMap;
10
11use crate::error::{Error, Result};
12
13pub trait Classifier {
16 fn id(&self, feature: &str) -> Option<u32>;
27
28 fn score(&self, features: &[u32]) -> f64;
39}
40
41impl<C: Classifier + ?Sized> Classifier for &C {
42 fn id(&self, feature: &str) -> Option<u32> {
43 (**self).id(feature)
44 }
45
46 fn score(&self, features: &[u32]) -> f64 {
47 (**self).score(features)
48 }
49}
50
51#[derive(Debug, Clone, PartialEq)]
64pub struct LinearClassifier {
65 ids: HashMap<String, u32>,
67 bias: f64,
69 weights: Vec<f64>,
71 pairs: HashMap<(u32, u32), f64>,
73}
74
75impl LinearClassifier {
76 pub fn new(
91 bias: f64,
92 features: HashMap<String, f64>,
93 pairs: HashMap<(String, String), f64>,
94 ) -> Result<Self> {
95 if !bias.is_finite() {
96 return Err(Error::Parser(format!("the bias {bias} is not finite")));
97 }
98 let mut names: Vec<&str> = features
101 .keys()
102 .map(String::as_str)
103 .chain(
104 pairs
105 .keys()
106 .flat_map(|(one, other)| [one.as_str(), other.as_str()]),
107 )
108 .collect();
109 names.sort_unstable();
110 names.dedup();
111 let ids: HashMap<String, u32> = names
112 .iter()
113 .enumerate()
114 .map(|(id, name)| (name.to_string(), id as u32))
115 .collect();
116
117 let mut weights = vec![0.0; names.len()];
118 for (name, weight) in &features {
119 if !weight.is_finite() {
120 return Err(Error::Parser(format!(
121 "the weight {weight} of {name:?} is not finite"
122 )));
123 }
124 weights[ids[name] as usize] = *weight;
125 }
126
127 let mut by_id = HashMap::new();
128 for ((one, other), weight) in &pairs {
129 if !weight.is_finite() {
130 return Err(Error::Parser(format!(
131 "the weight {weight} of the pair {one:?} and {other:?} is not finite"
132 )));
133 }
134 if one == other {
135 return Err(Error::Parser(format!(
136 "{one:?} is paired with itself: give its weight as a feature"
137 )));
138 }
139 let (low, high) = (ids[one].min(ids[other]), ids[one].max(ids[other]));
140 if by_id.insert((low, high), *weight).is_some() {
141 return Err(Error::Parser(format!(
142 "the pair {one:?} and {other:?} is given in both orders"
143 )));
144 }
145 }
146
147 Ok(Self {
148 ids,
149 bias,
150 weights,
151 pairs: by_id,
152 })
153 }
154
155 pub fn feature_count(&self) -> usize {
161 self.weights.len()
162 }
163
164 pub fn pair_count(&self) -> usize {
170 self.pairs.len()
171 }
172}
173
174impl Classifier for LinearClassifier {
175 fn id(&self, feature: &str) -> Option<u32> {
176 self.ids.get(feature).copied()
177 }
178
179 fn score(&self, features: &[u32]) -> f64 {
180 let mut score = self.bias;
181 for (index, &one) in features.iter().enumerate() {
182 score += self.weights.get(one as usize).copied().unwrap_or(0.0);
183 if self.pairs.is_empty() {
184 continue;
185 }
186 for &other in &features[index + 1..] {
187 let pair = (one.min(other), one.max(other));
188 score += self.pairs.get(&pair).copied().unwrap_or(0.0);
189 }
190 }
191 score
192 }
193}
194
195#[cfg(test)]
196mod tests {
197 use super::*;
198
199 fn classifier() -> LinearClassifier {
201 let features = HashMap::from([
202 ("a".to_string(), 1.0),
203 ("b".to_string(), -2.0),
204 ("c".to_string(), 4.0),
205 ]);
206 let pairs = HashMap::from([(("c".to_string(), "a".to_string()), 8.0)]);
207 LinearClassifier::new(0.5, features, pairs).unwrap()
208 }
209
210 fn ids(classifier: &LinearClassifier, names: &[&str]) -> Vec<u32> {
212 let mut ids: Vec<u32> = names
213 .iter()
214 .map(|name| classifier.id(name).unwrap())
215 .collect();
216 ids.sort_unstable();
217 ids
218 }
219
220 #[test]
221 fn the_score_adds_the_bias_the_features_and_the_pairs() {
222 let classifier = classifier();
223 assert_eq!(classifier.score(&[]), 0.5);
224 assert_eq!(classifier.score(&ids(&classifier, &["a"])), 1.5);
225 assert_eq!(classifier.score(&ids(&classifier, &["a", "b"])), -0.5);
226 assert_eq!(classifier.score(&ids(&classifier, &["a", "c"])), 13.5);
228 assert_eq!(classifier.score(&ids(&classifier, &["a", "b", "c"])), 11.5);
229 }
230
231 #[test]
232 fn an_unknown_feature_has_no_number() {
233 let classifier = classifier();
234 assert_eq!(classifier.id("d"), None);
235 assert_eq!(classifier.feature_count(), 3);
236 assert_eq!(classifier.pair_count(), 1);
237 }
238
239 #[test]
240 fn a_feature_named_in_a_pair_only_has_a_number() {
241 let pairs = HashMap::from([(("x".to_string(), "y".to_string()), 2.0)]);
242 let classifier = LinearClassifier::new(0.0, HashMap::new(), pairs).unwrap();
243 assert_eq!(classifier.feature_count(), 2);
244 assert_eq!(classifier.score(&ids(&classifier, &["x"])), 0.0);
245 assert_eq!(classifier.score(&ids(&classifier, &["x", "y"])), 2.0);
246 }
247
248 #[test]
249 fn the_numbers_follow_the_names() {
250 let classifier = classifier();
251 assert_eq!(classifier.id("a"), Some(0));
252 assert_eq!(classifier.id("b"), Some(1));
253 assert_eq!(classifier.id("c"), Some(2));
254 }
255
256 #[test]
257 fn weights_that_cannot_be_used_are_refused() {
258 let feature = |weight: f64| HashMap::from([("a".to_string(), weight)]);
259 let pair = |one: &str, other: &str, weight: f64| {
260 HashMap::from([((one.to_string(), other.to_string()), weight)])
261 };
262 let mut both = pair("a", "b", 1.0);
263 both.insert(("b".to_string(), "a".to_string()), 1.0);
264
265 let refused = [
266 (
267 "bias",
268 LinearClassifier::new(f64::NAN, HashMap::new(), HashMap::new()),
269 ),
270 (
271 "feature",
272 LinearClassifier::new(0.0, feature(f64::INFINITY), HashMap::new()),
273 ),
274 (
275 "pair",
276 LinearClassifier::new(0.0, HashMap::new(), pair("a", "b", f64::NAN)),
277 ),
278 (
279 "itself",
280 LinearClassifier::new(0.0, HashMap::new(), pair("a", "a", 1.0)),
281 ),
282 (
283 "both orders",
284 LinearClassifier::new(0.0, HashMap::new(), both),
285 ),
286 ];
287 let accepted: Vec<&str> = refused
288 .iter()
289 .filter(|(_, result)| !matches!(result, Err(Error::Parser(_))))
290 .map(|(name, _)| *name)
291 .collect();
292 assert!(accepted.is_empty(), "not refused: {accepted:?}");
293 }
294}