Skip to main content

lindera_dependency/parser/
classifier.rs

1//! The classifier of the parser: it scores the features of a decision.
2//!
3//! A classifier works in two steps, as the model of CaboCha does. It first
4//! gives a number to a feature string it knows ([`Classifier::id`]); the
5//! parser does this once for each bunsetsu of a sentence. It then scores the
6//! numbers of a decision ([`Classifier::score`]), without looking at a
7//! string.
8
9use std::collections::HashMap;
10
11use crate::error::{Error, Result};
12
13/// Scores the features of a decision: a source depends on a target when the
14/// score is above 0.
15pub trait Classifier {
16    /// The number of a feature.
17    ///
18    /// # Arguments
19    ///
20    /// * `feature` - The feature string.
21    ///
22    /// # Returns
23    ///
24    /// The number, or `None` for a feature the classifier does not know,
25    /// which the parser then leaves out.
26    fn id(&self, feature: &str) -> Option<u32>;
27
28    /// The score of a decision.
29    ///
30    /// # Arguments
31    ///
32    /// * `features` - The numbers of the features of the decision, in
33    ///   ascending order, each once.
34    ///
35    /// # Returns
36    ///
37    /// The score: above 0 when the source depends on the target.
38    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/// A linear classifier over features and pairs of features, with its
52/// weights in memory.
53///
54/// The score of a decision is the bias, plus the weight of each of its
55/// features, plus the weight of each pair of them. This is what the
56/// polynomial kernel of degree 2 of CaboCha and of J.DepP comes to once it
57/// is expanded.
58///
59/// It looks up every pair of the features of a decision in a hash table,
60/// which is enough to parse with weights made by hand. A trained model is
61/// a [`ParserModel`](super::ParserModel), and in a model file a
62/// [`ParserPart`](super::ParserPart).
63#[derive(Debug, Clone, PartialEq)]
64pub struct LinearClassifier {
65    /// The number of each feature.
66    ids: HashMap<String, u32>,
67    /// The bias.
68    bias: f64,
69    /// The weight of each feature, by its number.
70    weights: Vec<f64>,
71    /// The weight of each pair of features, the smaller number first.
72    pairs: HashMap<(u32, u32), f64>,
73}
74
75impl LinearClassifier {
76    /// Makes a classifier from its weights.
77    ///
78    /// # Arguments
79    ///
80    /// * `bias` - The bias.
81    /// * `features` - The weight of each feature.
82    /// * `pairs` - The weight of each pair of features, in either order. A
83    ///   feature named here only has the weight 0 on its own.
84    ///
85    /// # Returns
86    ///
87    /// The classifier, or [`Error::Parser`] for a weight that is not
88    /// finite, a pair of a feature with itself, or a pair given in both
89    /// orders.
90    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        // The numbers follow the order of the names, so that the same
99        // weights always give the same classifier.
100        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    /// The number of features the classifier knows.
156    ///
157    /// # Returns
158    ///
159    /// The number of features with a weight or in a pair.
160    pub fn feature_count(&self) -> usize {
161        self.weights.len()
162    }
163
164    /// The number of pairs of features with a weight.
165    ///
166    /// # Returns
167    ///
168    /// The number of pairs.
169    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    /// A classifier with the bias 0.5, three features and one pair.
200    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    /// The numbers of features, sorted.
211    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        // The pair of a and c adds 8.
227        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}