Skip to main content

clasificador/
clasificador.rs

1//! End-to-end: encode numeric features, train an HDC classifier (training = counting
2//! bits), save/load the model, and measure accuracy on synthetic data.
3//!
4//! Run with:  cargo run --release --example clasificador
5
6use holos_core::{Classifier, ItemMemory, LevelEncoder, Rng};
7
8fn uni(rng: &mut Rng) -> f64 {
9    (rng.next_u64() >> 11) as f64 / (1u64 << 53) as f64
10}
11
12fn sample(mean: &[f64], rng: &mut Rng) -> Vec<f64> {
13    mean.iter()
14        .map(|&m| (m + (uni(rng) - 0.5) * 0.2).clamp(0.0, 1.0))
15        .collect()
16}
17
18fn main() {
19    let d = 10_000;
20    let n_features = 16;
21    let n_classes = 5;
22    let mut rng = Rng::new(2025);
23
24    let enc = LevelEncoder::new(d, n_features, 0.0, 1.0, 20, &mut rng);
25    let means: Vec<Vec<f64>> = (0..n_classes)
26        .map(|_| (0..n_features).map(|_| uni(&mut rng)).collect())
27        .collect();
28
29    // Train: just count bits per class.
30    let mut clf = Classifier::new(d);
31    for c in 0..n_classes {
32        for _ in 0..50 {
33            let s = sample(&means[c], &mut rng);
34            clf.train(&enc.encode(&s), &format!("class{c}"));
35        }
36    }
37    println!(
38        "Trained {} classes by COUNTING BITS (no gradients, no epochs).",
39        clf.n_classes()
40    );
41
42    // Serialize the model and reload it (deploy-once, use-many).
43    let bytes = clf.build().save();
44    let model = ItemMemory::load(&bytes).unwrap();
45    println!("Model serialized to {} bytes and reloaded OK.", bytes.len());
46
47    // Test accuracy.
48    let per_class = 100;
49    let mut correct = 0;
50    for c in 0..n_classes {
51        for _ in 0..per_class {
52            let s = sample(&means[c], &mut rng);
53            if model.cleanup(&enc.encode(&s)).unwrap().0 == format!("class{c}") {
54                correct += 1;
55            }
56        }
57    }
58    let total = n_classes * per_class;
59    println!(
60        "Accuracy on {} test samples: {:.1}%",
61        total,
62        100.0 * correct as f64 / total as f64
63    );
64}