randomforest/
functions.rs1use ordered_float::OrderedFloat;
2use std::collections::HashMap;
3
4pub fn mean(xs: impl Iterator<Item = f64>) -> f64 {
5 let mut count = 0;
6 let mut total = 0.0;
7 for x in xs {
8 count += 1;
9 total += x;
10 }
11 assert_ne!(count, 0);
12 total / count as f64
13}
14
15pub fn most_frequent(xs: impl Iterator<Item = f64>) -> f64 {
16 let (histogram, _) = histogram(xs);
17 histogram
18 .into_iter()
19 .max_by_key(|t| t.1)
20 .map(|t| (t.0).0)
21 .expect("unreachable")
22}
23
24pub fn histogram(xs: impl Iterator<Item = f64>) -> (HashMap<OrderedFloat<f64>, usize>, usize) {
25 let mut histogram = HashMap::<_, usize>::new();
26 let mut n = 0;
27 for x in xs {
28 *histogram.entry(OrderedFloat(x)).or_default() += 1;
29 n += 1;
30 }
31 (histogram, n)
32}