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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::hash_map::Keys;
use std::iter::FromIterator;
use std::vec::Vec;

struct Attributes {
    attributes: HashMap<String, HashMap<String, i64>>,
}

impl Attributes {
    pub fn new() -> Attributes {
        Attributes {
            attributes: HashMap::new(),
        }
    }

    fn add(&mut self, attribute: &String, label: &String) {
        let labels = self.attributes
            .entry(attribute.to_string())
            .or_insert(HashMap::new());
        let value = labels.entry((*label).to_string()).or_insert(0);
        *value += 1;
    }

    fn get_frequency(&mut self, attribute: &String, label: &String) -> (Option<&i64>, bool) {
        match self.attributes.get(attribute) {
            Some(labels) => match labels.get(label) {
                Some(value) => return (Some(value), true),
                None => return (None, true),
            },
            None => return (None, false),
        }
    }
}

struct Labels {
    counts: HashMap<String, i64>,
}

impl Labels {
    pub fn new() -> Labels {
        Labels {
            counts: HashMap::new(),
        }
    }

    fn add(&mut self, label: &String) {
        let value = self.counts.entry(label.to_string()).or_insert(0);
        *value += 1;
    }

    fn get_count(&mut self, label: &String) -> Option<&i64> {
        return self.counts.get(label);
    }

    fn get_labels(&mut self) -> Keys<String, i64> {
        return self.counts.keys();
    }

    fn get_total(&mut self) -> i64 {
        return self.counts.values().fold(0, |acc, x| acc + x);
    }
}

struct Model {
    labels: Labels,
    attributes: Attributes,
}

impl Model {
    pub fn new() -> Model {
        Model {
            labels: Labels::new(),
            attributes: Attributes::new(),
        }
    }
    fn train(&mut self, data: &Vec<String>, label: &String) {
        self.labels.add(label);
        for attribute in data {
            self.attributes.add(attribute, label);
        }
    }
}

pub struct NaiveBayes {
    model: Model,
    minimum_probability: f64,
    minimum_log_probability: f64
}

impl NaiveBayes {
    /// creates a new instance of a `NaiveBayes` classifier.
    pub fn new() -> NaiveBayes {
        NaiveBayes {
            model: Model::new(),
            minimum_probability: 1e-9,
            minimum_log_probability: -100.0,
        }
    }

    fn prior(&mut self, label: &String) -> Option<f64> {
        let total = *(&self.model.labels.get_total()) as f64;
        let label = &self.model.labels.get_count(label);
        if label.is_some() && total > 0.0 {
            return Some(*label.unwrap() as f64 / total);
        } else {
            return None;
        }
    }

    fn log_prior(&mut self, label: &String) -> Option<f64> {
        let total = *(&self.model.labels.get_total()) as f64;
        let label = &self.model.labels.get_count(label);
        if label.is_some() && total > 0.0 {
            return Some((*label.unwrap() as f64).ln() - total.ln());
        } else {
            return None;
        }
    }

    fn calculate_attr_prob(&mut self, attribute: &String, label: &String) -> Option<f64> {
        match self.model.attributes.get_frequency(attribute, label) {
            (Some(frequency), true) => match self.model.labels.get_count(label) {
                Some(count) => return Some((*frequency as f64) / (*count as f64)),
                None => return None,
            },
            (None, true) => return Some(self.minimum_probability),
            (None, false) => return None,
            (Some(_), false) => None,
        }
    }

    fn calculate_attr_log_prob(&mut self, attribute: &String, label: &String) -> Option<f64> {
        match self.model.attributes.get_frequency(attribute, label) {
            (Some(frequency), true) => match self.model.labels.get_count(label) {
                Some(count) => return Some((*frequency as f64).ln() - (*count as f64).ln()),
                None => return None,
            },
            (None, true) => return Some(self.minimum_log_probability),
            (None, false) => return None,
            (Some(_), false) => None,
        }
    }

    fn label_prob(&mut self, label: &String, attrs: &HashSet<String>) -> Vec<f64> {
        let mut probs: Vec<f64> = Vec::new();
        for attr in attrs {
            match self.calculate_attr_prob(attr, label) {
                Some(p) => {
                    probs.push(p);
                }
                None => {}
            }
        }
        return probs;
    }

    fn label_log_prob(&mut self, label: &String, attrs: &HashSet<String>) -> Vec<f64> {
        let mut probs: Vec<f64> = Vec::new();
        for attr in attrs {
            match self.calculate_attr_log_prob(attr, label) {
                Some(p) => {
                    probs.push(p);
                }
                None => {}
            }
        }
        return probs;
    }

    /// trains the model with a `Vec<String>` of tokens, associating it with a `String` label.
    pub fn train(&mut self, data: &Vec<String>, label: &String) {
        self.model.train(data, label);
    }

    /// classify a `Vec<String>` of tokens returning a map of tokens and probabilities
    /// as keys and values, respectively.
    pub fn classify(&mut self, data: &Vec<String>) -> HashMap<String, f64> {
        let attribute_set: HashSet<String> = HashSet::from_iter(data.iter().cloned());
        let mut result: HashMap<String, f64> = HashMap::new();
        let labels: HashSet<String> =
            HashSet::from_iter(self.model.labels.get_labels().into_iter().cloned());
        for label in labels {
            let p = self.label_prob(&label, &attribute_set);
            let p_iter = p.into_iter().fold(1.0, |acc, x| acc * x);
            let _value = result
                .entry(label.to_string())
                .or_insert(p_iter * self.prior(&label).unwrap());
        }

        return result;
    }

    /// classify a `Vec<String>` of tokens returning a map of tokens and log-probabilities
    /// as keys and values, respectively. Using `log_classify` may prevent underflows.
    pub fn log_classify(&mut self, data: &Vec<String>) -> HashMap<String, f64> {
        let attribute_set: HashSet<String> = HashSet::from_iter(data.iter().cloned());
        let mut result: HashMap<String, f64> = HashMap::new();
        let labels: HashSet<String> =
            HashSet::from_iter(self.model.labels.get_labels().into_iter().cloned());
        for label in labels {
            let p = self.label_log_prob(&label, &attribute_set);
            let max = p.iter().cloned().fold(-1./0. /* inf */, f64::max);
            let p_iter = p.into_iter().fold(0.0, |acc, x| acc + (x - max).exp());
            let _value = result
                .entry(label.to_string())
                .or_insert(max + p_iter.ln() + self.log_prior(&label).unwrap());
        }

        return result;
    }
}

#[cfg(test)]
mod test_attributes {
    use super::*;

    #[test]
    fn attribute_add() {
        let mut model = Attributes::new();
        model.add(&"rust".to_string(), &"naive".to_string());
        assert_eq!(
            *model
                .get_frequency(&"rust".to_string(), &"naive".to_string())
                .0
                .unwrap(),
            1
        );
    }

    #[test]
    fn get_non_existing() {
        let mut model = Attributes::new();
        assert_eq!(
            model
                .get_frequency(&"rust".to_string(), &"naive".to_string())
                .0,
            None
        );
    }

}

#[cfg(test)]
mod test_labels {

    use super::*;

    #[test]
    fn label_add() {
        let mut labels = Labels::new();
        labels.add(&"rust".to_string());
        assert_eq!(*labels.get_count(&"rust".to_string()).unwrap(), 1);
    }

    #[test]
    fn label_get_nonexistent() {
        let mut labels = Labels::new();
        assert_eq!(labels.get_count(&"rust".to_string()), None);
    }

    #[test]
    fn get_labels() {
        let mut labels = Labels::new();
        labels.add(&"rust".to_string());
        assert_eq!(labels.get_labels().len(), 1);
        assert_eq!(labels.get_labels().last().unwrap(), "rust");
    }

    #[test]
    fn get_counts() {
        let mut labels = Labels::new();
        labels.add(&"rust".to_string());
        labels.add(&"rust".to_string());
        assert_eq!(labels.get_labels().len(), 1);
        assert_eq!(*labels.get_count(&"rust".to_string()).unwrap(), 2);
    }

    #[test]
    fn get_nonexistent_counts() {
        let mut labels = Labels::new();
        assert_eq!(labels.get_labels().len(), 0);
        assert_eq!(labels.get_count(&"rust".to_string()), None);
    }

    #[test]
    fn get_nonexistent_total() {
        let mut labels = Labels::new();
        assert_eq!(labels.get_total(), 0);
    }

    #[test]
    fn get_total() {
        let mut labels = Labels::new();
        labels.add(&"rust".to_string());
        labels.add(&"rust".to_string());
        labels.add(&"naive".to_string());
        labels.add(&"bayes".to_string());
        assert_eq!(labels.get_total(), 4);
    }

}

#[cfg(test)]
mod test_naive_bayes {
    use super::*;
    use std::f64::consts::LN_2;

    #[test]
    fn test_prior() {
        let mut nb = NaiveBayes::new();
        let mut data: Vec<String> = Vec::new();
        data.push("rust".to_string());
        data.push("naive".to_string());
        data.push("bayes".to_string());
        nb.model.train(&data, &"👍".to_string());
        let prior = nb.prior(&"👍".to_string());
        assert_eq!(prior, Some(1.0));
    }

    #[test]
    fn test_log_prior() {
        let mut nb = NaiveBayes::new();
        let mut data: Vec<String> = Vec::new();
        data.push("rust".to_string());
        data.push("naive".to_string());
        data.push("bayes".to_string());
        nb.model.train(&data, &"👍".to_string());
        let prior = nb.log_prior(&"👍".to_string());
        assert_eq!(prior, Some(0.0));
    }

    #[test]
    fn test_prior_nonexistent() {
        let mut nb = NaiveBayes::new();
        let mut data: Vec<String> = Vec::new();
        data.push("rust".to_string());
        data.push("naive".to_string());
        data.push("bayes".to_string());
        nb.model.train(&data, &"👍".to_string());
        let prior = nb.prior(&"👎".to_string());
        assert_eq!(prior, None);
    }

    #[test]
    fn test_classification() {
        let mut nb = NaiveBayes::new();
        let mut data: Vec<String> = Vec::new();
        data.push("rust".to_string());
        data.push("naive".to_string());
        data.push("bayes".to_string());
        nb.model.train(&data, &"👍".to_string());
        let mut data2: Vec<String> = Vec::new();
        data2.push("golang".to_string());
        data2.push("java".to_string());
        data2.push("javascript".to_string());
        nb.model.train(&data2, &"👎".to_string());

        let classes = nb.classify(
            &(vec![
                "rust".to_string(),
                "scala".to_string(),
                "c++".to_string(),
            ]),
        );
        assert_eq!(classes.get(&"👍".to_string()).unwrap(), &0.5);
        assert_eq!(classes.get(&"👎".to_string()).unwrap(), &0.0000000005);
        print!("{:?}", classes);

    }

    #[test]
    fn test_log_classification() {
        let mut nb = NaiveBayes::new();
        let mut data: Vec<String> = Vec::new();
        data.push("rust".to_string());
        data.push("naive".to_string());
        data.push("bayes".to_string());
        nb.model.train(&data, &"👍".to_string());
        let mut data2: Vec<String> = Vec::new();
        data2.push("golang".to_string());
        data2.push("java".to_string());
        data2.push("javascript".to_string());
        nb.model.train(&data2, &"👎".to_string());

        let classes = nb.log_classify(
            &(vec![
                "rust".to_string(),
                "scala".to_string(),
                "c++".to_string(),
            ]),
        );
        assert_eq!(classes.get(&"👍".to_string()).unwrap(), &-LN_2);
        assert_eq!(classes.get(&"👎".to_string()).unwrap(), &-100.69314718055995);
        print!("{:?}", classes);

    }

}