pub struct LevelEncoder { /* private fields */ }Expand description
Encodes fixed-length numeric feature vectors into hypervectors.
Implementations§
Source§impl LevelEncoder
impl LevelEncoder
Sourcepub fn new(
d: usize,
n_features: usize,
min: f64,
max: f64,
n_levels: usize,
rng: &mut Rng,
) -> Self
pub fn new( d: usize, n_features: usize, min: f64, max: f64, n_levels: usize, rng: &mut Rng, ) -> Self
Build an encoder for n_features values in [min, max], quantized to n_levels.
Examples found in repository?
examples/clasificador.rs (line 24)
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}More examples
examples/digits.rs (line 33)
8fn main() {
9 // Dataset shipped with the crate: 64 pixel values (0..16) + label, per line.
10 let csv = include_str!("data/digits.csv");
11 let mut rows: Vec<(Vec<f64>, String)> = Vec::new();
12 for line in csv.lines() {
13 if line.trim().is_empty() {
14 continue;
15 }
16 let mut nums: Vec<i64> = line.split(',').map(|t| t.trim().parse().unwrap()).collect();
17 let label = nums.pop().unwrap().to_string();
18 let features: Vec<f64> = nums.iter().map(|&v| v as f64).collect();
19 rows.push((features, label));
20 }
21
22 // Deterministic shuffle, then a 70/30 train/test split.
23 let mut rng = Rng::new(7);
24 for k in (1..rows.len()).rev() {
25 let j = (rng.next_u64() as usize) % (k + 1);
26 rows.swap(k, j);
27 }
28 let n_train = rows.len() * 7 / 10;
29 let (train, test) = rows.split_at(n_train);
30
31 // Encode: 64 features, pixel intensity 0..16 quantized to 16 levels.
32 let d = 10_000;
33 let enc = LevelEncoder::new(d, 64, 0.0, 16.0, 16, &mut rng);
34
35 let train_hv: Vec<Hypervector> = train.iter().map(|(f, _)| enc.encode(f)).collect();
36 let train_labels: Vec<&str> = train.iter().map(|(_, l)| l.as_str()).collect();
37 let test_hv: Vec<Hypervector> = test.iter().map(|(f, _)| enc.encode(f)).collect();
38 let test_labels: Vec<&str> = test.iter().map(|(_, l)| l.as_str()).collect();
39
40 let accuracy = |model: &ItemMemory| -> f64 {
41 let correct = test_hv
42 .iter()
43 .zip(&test_labels)
44 .filter(|(hv, &truth)| model.cleanup(hv).unwrap().0 == truth)
45 .count();
46 correct as f64 / test_hv.len() as f64
47 };
48
49 // One-shot training (single pass).
50 let mut clf = Classifier::new(d);
51 for (hv, &l) in train_hv.iter().zip(&train_labels) {
52 clf.train(hv, l);
53 }
54 let acc_oneshot = accuracy(&clf.build());
55
56 // Adaptive retraining.
57 let mut clf2 = Classifier::new(d);
58 clf2.fit(&train_hv, &train_labels, 20);
59 let acc_retrained = accuracy(&clf2.build());
60
61 println!(
62 "Handwritten digits: {} train / {} test, 10 classes",
63 train.len(),
64 test.len()
65 );
66 println!("HDC one-shot : {:.1}%", 100.0 * acc_oneshot);
67 println!("HDC + retraining : {:.1}%", 100.0 * acc_retrained);
68}Sourcepub fn encode(&self, features: &[f64]) -> Hypervector
pub fn encode(&self, features: &[f64]) -> Hypervector
Encode one feature vector (its length must equal n_features).
Examples found in repository?
examples/clasificador.rs (line 34)
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}More examples
examples/digits.rs (line 35)
8fn main() {
9 // Dataset shipped with the crate: 64 pixel values (0..16) + label, per line.
10 let csv = include_str!("data/digits.csv");
11 let mut rows: Vec<(Vec<f64>, String)> = Vec::new();
12 for line in csv.lines() {
13 if line.trim().is_empty() {
14 continue;
15 }
16 let mut nums: Vec<i64> = line.split(',').map(|t| t.trim().parse().unwrap()).collect();
17 let label = nums.pop().unwrap().to_string();
18 let features: Vec<f64> = nums.iter().map(|&v| v as f64).collect();
19 rows.push((features, label));
20 }
21
22 // Deterministic shuffle, then a 70/30 train/test split.
23 let mut rng = Rng::new(7);
24 for k in (1..rows.len()).rev() {
25 let j = (rng.next_u64() as usize) % (k + 1);
26 rows.swap(k, j);
27 }
28 let n_train = rows.len() * 7 / 10;
29 let (train, test) = rows.split_at(n_train);
30
31 // Encode: 64 features, pixel intensity 0..16 quantized to 16 levels.
32 let d = 10_000;
33 let enc = LevelEncoder::new(d, 64, 0.0, 16.0, 16, &mut rng);
34
35 let train_hv: Vec<Hypervector> = train.iter().map(|(f, _)| enc.encode(f)).collect();
36 let train_labels: Vec<&str> = train.iter().map(|(_, l)| l.as_str()).collect();
37 let test_hv: Vec<Hypervector> = test.iter().map(|(f, _)| enc.encode(f)).collect();
38 let test_labels: Vec<&str> = test.iter().map(|(_, l)| l.as_str()).collect();
39
40 let accuracy = |model: &ItemMemory| -> f64 {
41 let correct = test_hv
42 .iter()
43 .zip(&test_labels)
44 .filter(|(hv, &truth)| model.cleanup(hv).unwrap().0 == truth)
45 .count();
46 correct as f64 / test_hv.len() as f64
47 };
48
49 // One-shot training (single pass).
50 let mut clf = Classifier::new(d);
51 for (hv, &l) in train_hv.iter().zip(&train_labels) {
52 clf.train(hv, l);
53 }
54 let acc_oneshot = accuracy(&clf.build());
55
56 // Adaptive retraining.
57 let mut clf2 = Classifier::new(d);
58 clf2.fit(&train_hv, &train_labels, 20);
59 let acc_retrained = accuracy(&clf2.build());
60
61 println!(
62 "Handwritten digits: {} train / {} test, 10 classes",
63 train.len(),
64 test.len()
65 );
66 println!("HDC one-shot : {:.1}%", 100.0 * acc_oneshot);
67 println!("HDC + retraining : {:.1}%", 100.0 * acc_retrained);
68}Auto Trait Implementations§
impl Freeze for LevelEncoder
impl RefUnwindSafe for LevelEncoder
impl Send for LevelEncoder
impl Sync for LevelEncoder
impl Unpin for LevelEncoder
impl UnsafeUnpin for LevelEncoder
impl UnwindSafe for LevelEncoder
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more