Skip to main content

iris/common/
iris_driver.rs

1//! The iris example's program, shared by `examples/iris.rs` (which parses the
2//! command line) and `tests/iris_golden.rs` (which runs it in-process against the
3//! C++ goldens). Port of tinymind (C++) `examples/iris/iris.cpp`; see `examples/iris.rs`.
4
5use std::fs::{self, File};
6use std::io::{self, BufWriter, Write};
7use std::path::Path;
8
9use tinymind::rand::GlibcRand;
10use tinymind::{MultilayerPerceptron, Q16_16, Relu, Sigmoid};
11
12#[path = "cppfmt.rs"]
13mod cppfmt;
14use cppfmt::{fmt_fixed, fmt_g};
15
16const NUMBER_OF_INPUTS: usize = 4;
17const NUMBER_OF_NEURONS_PER_HIDDEN_LAYER: usize = 8;
18const NUMBER_OF_OUTPUTS: usize = 3;
19
20type NeuralNetwork = MultilayerPerceptron<
21    Q16_16,
22    Relu,
23    Sigmoid,
24    NUMBER_OF_INPUTS,
25    NUMBER_OF_NEURONS_PER_HIDDEN_LAYER,
26    NUMBER_OF_OUTPUTS,
27>;
28
29/// C++ `WEIGHT_INIT_SEED`: seeds the initial weights only.
30const WEIGHT_INIT_SEED: u32 = 1;
31/// Seeds the shuffle and the training-sample draws.
32const RANDOM_SEED: u32 = 7;
33const ITERATIONS: u32 = 30_000;
34const REPORT_EVERY: u32 = 1_000;
35const CLASS_NAMES: [&str; NUMBER_OF_OUTPUTS] = ["setosa", "versicolor", "virginica"];
36
37#[derive(Clone, Copy)]
38struct Sample {
39    /// Sepal length and width, petal length and width (cm).
40    feat: [f64; 4],
41    /// 0 = setosa, 1 = versicolor, 2 = virginica.
42    label: usize,
43}
44
45/// Per-feature z-score statistics fit on the training split.
46struct FeatureStats {
47    mean: [f64; 4],
48    stdev: [f64; 4],
49}
50
51/// Train on `data_path`, evaluate, write the three CSV files into `out_dir` and
52/// the training log and accuracy to `stdout`.
53pub fn run(out_dir: &Path, data_path: &Path, stdout: &mut dyn Write) -> io::Result<()> {
54    // As in the xor port: the C++ seeds rand() with WEIGHT_INIT_SEED, builds the
55    // network (drawing its weights), then re-seeds with 7. Two generators here.
56    let mut init_rng = GlibcRand::new(WEIGHT_INIT_SEED);
57    let mut nn = NeuralNetwork::new(|| random_weight(init_rng.next_i32()));
58
59    let Some(mut data) = load_csv(data_path) else {
60        return Err(io::Error::new(
61            io::ErrorKind::InvalidData,
62            format!("could not open or parse {}", data_path.display()),
63        ));
64    };
65    // The C++ names the file it opens from the working directory.
66    writeln!(stdout, "Loaded {} rows from iris.data.", data.len())?;
67
68    // Deterministic shuffle + 80/20 split (the C++ re-seeds with 7 just before).
69    let mut rng = GlibcRand::new(RANDOM_SEED);
70    for i in (2..=data.len()).rev() {
71        let j = rng.next_i32() as usize % i;
72        data.swap(i - 1, j);
73    }
74    let n_train = data.len() * 4 / 5;
75    let (train, test) = data.split_at(n_train);
76    writeln!(stdout, "Train: {}  Test: {}", train.len(), test.len())?;
77
78    let stats = fit_stats(train);
79
80    // ---- Training ----
81    let mut loss_csv = BufWriter::new(File::create(out_dir.join("iris_loss.csv"))?);
82    writeln!(loss_csv, "iter,avg_err")?;
83    let mut err_sum = 0.0;
84    for it in 0..ITERATIONS {
85        let s = &train[rng.next_i32() as usize % train.len()];
86        let input = to_input(s, &stats);
87        let target: [Q16_16; NUMBER_OF_OUTPUTS] =
88            core::array::from_fn(|k| to_q(if s.label == k { 1.0 } else { 0.0 }));
89
90        nn.feed_forward(&input);
91        let err = nn.calculate_error(&target);
92        if !err.is_within_zero_tolerance() {
93            nn.train(&target);
94        }
95        err_sum += err.to_f64().abs();
96
97        if (it + 1) % REPORT_EVERY == 0 {
98            let avg = err_sum / f64::from(REPORT_EVERY);
99            writeln!(
100                stdout,
101                "iter {:>6}   avg|err| = {}",
102                it + 1,
103                fmt_fixed(avg, 4)
104            )?;
105            writeln!(loss_csv, "{},{}", it + 1, fmt_g(avg))?;
106            err_sum = 0.0;
107        }
108    }
109    loss_csv.flush()?;
110
111    // ---- Evaluation ----
112    let mut confusion = [[0u32; NUMBER_OF_OUTPUTS]; NUMBER_OF_OUTPUTS];
113    let mut scatter = BufWriter::new(File::create(out_dir.join("iris_scatter.csv"))?);
114    writeln!(scatter, "petal_len,petal_width,true_class,pred_class")?;
115    let mut correct = 0;
116    for s in test {
117        nn.feed_forward(&to_input(s, &stats));
118        let learned = nn.learned_values();
119        // First index wins ties, as the C++ strict `>` scan does.
120        let mut pred = 0;
121        let mut best = learned[0].to_f64();
122        for (k, value) in learned.iter().enumerate().skip(1) {
123            let v = value.to_f64();
124            if v > best {
125                best = v;
126                pred = k;
127            }
128        }
129        confusion[s.label][pred] += 1;
130        if pred == s.label {
131            correct += 1;
132        }
133        writeln!(
134            scatter,
135            "{},{},{},{}",
136            fmt_g(s.feat[2]),
137            fmt_g(s.feat[3]),
138            s.label,
139            pred
140        )?;
141    }
142    scatter.flush()?;
143
144    let mut cm = BufWriter::new(File::create(out_dir.join("iris_confusion.csv"))?);
145    writeln!(cm, "actual,pred_setosa,pred_versicolor,pred_virginica")?;
146    for (name, row) in CLASS_NAMES.iter().zip(&confusion) {
147        write!(cm, "{name}")?;
148        for count in row {
149            write!(cm, ",{count}")?;
150        }
151        writeln!(cm)?;
152    }
153    cm.flush()?;
154
155    let acc = f64::from(correct) / test.len() as f64;
156    writeln!(
157        stdout,
158        "\nTest accuracy: {}  ({correct}/{})",
159        fmt_fixed(acc, 4),
160        test.len()
161    )?;
162    stdout.flush()
163}
164
165/// Symmetric small init in [-0.5, 0.5] raw Q16.16 units (C++ `RandomNumberGenerator`).
166fn random_weight(rand: i32) -> Q16_16 {
167    let half = Q16_16::ONE.raw() / 2;
168    Q16_16::from_raw(rand % (2 * half + 1) - half)
169}
170
171/// C++ `toQ`: `lround(v * 2^16)`. `f64::round` rounds halves away from zero, as
172/// `lround` does.
173fn to_q(v: f64) -> Q16_16 {
174    Q16_16::from_raw((v * 65536.0).round() as i32)
175}
176
177/// z-score, then /3 so typical values sit inside Q16.16's stable range.
178fn to_input(s: &Sample, stats: &FeatureStats) -> [Q16_16; NUMBER_OF_INPUTS] {
179    core::array::from_fn(|f| to_q((s.feat[f] - stats.mean[f]) / stats.stdev[f] / 3.0))
180}
181
182/// Mean and population standard deviation per feature, summed in the C++ order.
183fn fit_stats(train: &[Sample]) -> FeatureStats {
184    let mut mean = [0.0; 4];
185    let mut stdev = [0.0; 4];
186    for s in train {
187        for (m, x) in mean.iter_mut().zip(s.feat) {
188            *m += x;
189        }
190    }
191    let n = train.len() as f64;
192    for m in &mut mean {
193        *m /= n;
194    }
195    for s in train {
196        for ((sd, x), m) in stdev.iter_mut().zip(s.feat).zip(mean) {
197            let d = x - m;
198            *sd += d * d;
199        }
200    }
201    for sd in &mut stdev {
202        *sd = (*sd / n).sqrt();
203        if *sd < 1e-6 {
204            *sd = 1.0;
205        }
206    }
207    FeatureStats { mean, stdev }
208}
209
210/// C++ `loadCsv`: 4 numbers and a species name per line; blank lines, short lines
211/// and unknown species are skipped. `None` if the file cannot be read or has no
212/// usable rows.
213fn load_csv(path: &Path) -> Option<Vec<Sample>> {
214    let text = fs::read_to_string(path).ok()?;
215    let mut out = Vec::new();
216    for line in text.lines() {
217        let cells: Vec<&str> = line.split(',').collect();
218        if line.is_empty() || cells.len() < 5 {
219            continue;
220        }
221        let mut feat = [0.0; 4];
222        for (f, cell) in feat.iter_mut().zip(&cells) {
223            *f = cell.trim().parse().ok()?;
224        }
225        let name = cells[4];
226        let label = if name.contains("setosa") {
227            0
228        } else if name.contains("versicolor") {
229            1
230        } else if name.contains("virginica") {
231            2
232        } else {
233            continue;
234        };
235        out.push(Sample { feat, label });
236    }
237    (!out.is_empty()).then_some(out)
238}