Skip to main content

MultilayerPerceptron

Struct MultilayerPerceptron 

Source
pub struct MultilayerPerceptron<V, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt = Sgd> { /* private fields */ }
Expand description

IN inputs -> HID hidden neurons (activation H) -> OUT outputs (activation O).

C++: MultilayerPerceptron<ValueType, IN, 1, HID, OUT, TransferFunctions>.

Opt is the optimizer: Sgd (the default) or an adaptive one from optimizer, passed to with_optimizer.

Implementations§

Source§

impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize> MultilayerPerceptron<V, H, O, IN, HID, OUT, Sgd>
where V: Fixed, H: Activation<V>, O: Activation<V>,

Source

pub fn new(random_weight: impl FnMut() -> V) -> Self

Build the network, trained with Sgd, and initialise its weights from random_weight, in the same order as the C++ constructor: input neurons, input bias, hidden neurons, hidden bias, output neurons.

The C++ code reaches a static generateRandomWeight() policy that reads global rand() state; passing a closure makes that dependency explicit.

Examples found in repository?
examples/common/xor_driver.rs (line 124)
107fn run<V: Format>(
108    out_dir: &Path,
109    learning_rate: Option<f64>,
110    momentum: Option<f64>,
111    stdout: &mut dyn Write,
112) -> io::Result<()>
113where
114    Tanh: Activation<V>,
115    Sigmoid: Activation<V>,
116{
117    // The C++ example seeds rand() twice: srand(WEIGHT_INIT_SEED = 1), construct
118    // the network (which draws the initial weights), then srand(7) for the
119    // training samples. Re-seeding a global generator becomes two independent
120    // generator values in Rust. (The two seeds exist because the C++ network used
121    // to be a global, built before main() seeded rand(), i.e. from glibc's default
122    // seed of 1; tinymind PR #236 made that explicit without changing any output.)
123    let mut init_rng = GlibcRand::new(WEIGHT_INIT_SEED);
124    let mut nn = NeuralNetwork::<V>::new(|| V::random_weight(init_rng.next_i32()));
125    let mut rng = GlibcRand::new(RANDOM_SEED);
126    if let Some(lr) = learning_rate {
127        nn.set_learning_rate(V::from_f64_trunc(lr));
128    }
129    if let Some(m) = momentum {
130        nn.set_momentum_rate(V::from_f64_trunc(m));
131    }
132
133    let mut results = BufWriter::new(File::create(out_dir.join("nn_fixed_xor.txt"))?);
134    let mut curve = BufWriter::new(File::create(out_dir.join("xor_training.csv"))?);
135    writeln!(curve, "iteration,avg_error")?;
136
137    write_header(&mut results)?;
138
139    let mut avg_error = V::ZERO;
140    for i in 0..TRAINING_ITERATIONS {
141        let (inputs, target) = generate_xor_training_value::<V>(&mut rng);
142
143        nn.feed_forward(&inputs);
144        let error = nn.calculate_error(&target);
145        if !error.is_within_zero_tolerance() {
146            nn.train(&target);
147        }
148        let learned = nn.learned_values();
149
150        store_network_properties(&nn, &mut results, &target, &learned)?;
151        writeln!(results, "{error}")?;
152
153        // Accumulate |error| in raw LSBs; the average divides it back down.
154        avg_error += error.abs();
155        if (i + 1) % NUM_SAMPLES_AVG_ERROR == 0 {
156            avg_error = avg_error / V::from_int(NUM_SAMPLES_AVG_ERROR as i32);
157            writeln!(stdout, "Iteration: {} Average Error: {}", i + 1, avg_error)?;
158            writeln!(curve, "{},{}", i + 1, fmt_g(evaluate_xor_error(&mut nn)))?;
159            avg_error = V::ZERO;
160        }
161    }
162
163    // Success = every XOR pattern lands on the correct side of 0.5.
164    let mut correct = 0;
165    for [a, b, expected] in XOR_CASES {
166        let pred = predict(&mut nn, V::from_int(a), V::from_int(b));
167        let ok = (pred >= 0.5) == (expected == 1);
168        correct += u32::from(ok);
169        writeln!(
170            stdout,
171            "  {a} ^ {b} = {expected}  pred={}{}",
172            fmt_g(pred),
173            if ok { "  ok" } else { "  WRONG" }
174        )?;
175    }
176    writeln!(
177        stdout,
178        "{correct}/4 patterns classified correctly. Final 4-case error: {}",
179        fmt_g(evaluate_xor_error(&mut nn))
180    )?;
181
182    // Decision surface over the [0,1]^2 grid.
183    let mut surf = BufWriter::new(File::create(out_dir.join("xor_decision_surface.csv"))?);
184    writeln!(surf, "x0,x1,prob")?;
185    const G: i32 = 41;
186    for a in 0..G {
187        for b in 0..G {
188            let x0 = f64::from(a) / f64::from(G - 1);
189            let x1 = f64::from(b) / f64::from(G - 1);
190            let prob = predict(&mut nn, V::from_f64_trunc(x0), V::from_f64_trunc(x1));
191            writeln!(surf, "{},{},{}", fmt_g(x0), fmt_g(x1), fmt_g(prob))?;
192        }
193    }
194
195    // Flush explicitly so a write error is reported rather than lost in Drop.
196    results.flush()?;
197    curve.flush()?;
198    surf.flush()?;
199    stdout.flush()
200}
More examples
Hide additional examples
examples/common/iris_driver.rs (line 57)
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}
examples/common/energy_driver.rs (line 62)
58pub fn run(out_dir: &Path, data_path: &Path, stdout: &mut dyn Write) -> io::Result<()> {
59    // The C++ seeds rand() with WEIGHT_INIT_SEED, builds the network (drawing
60    // its weights), then re-seeds with 7. Two generators here.
61    let mut init_rng = GlibcRand::new(WEIGHT_INIT_SEED);
62    let mut nn = NeuralNetwork::new(|| random_weight(init_rng.next_i32()));
63
64    let Some(mut data) = load_csv(data_path) else {
65        return Err(io::Error::new(
66            io::ErrorKind::InvalidData,
67            format!("could not open or parse {}", data_path.display()),
68        ));
69    };
70    writeln!(stdout, "Loaded {} rows from ENB2012_data.csv.", data.len())?;
71
72    // Deterministic shuffle + 80/20 split.
73    let mut rng = GlibcRand::new(RANDOM_SEED);
74    for i in (2..=data.len()).rev() {
75        let j = rng.next_i32() as usize % i;
76        data.swap(i - 1, j);
77    }
78    let n_train = data.len() * 4 / 5;
79    let (train, test) = data.split_at(n_train);
80    writeln!(stdout, "Train: {}  Test: {}", train.len(), test.len())?;
81
82    let feat_stats = fit_stats(train, |s| s.feat);
83    let target_stats = fit_stats(train, |s| s.load);
84
85    // A modest learning rate, no momentum or acceleration, and gradients
86    // clipped to [-1, 1] (C++ GradientClipByValue<ValueType>): a linear output's
87    // unbounded gradient otherwise saturates Q16.16.
88    nn.set_learning_rate(to_q(0.02));
89    nn.set_momentum_rate(to_q(0.0));
90    nn.set_acceleration_rate(to_q(0.0));
91    nn.set_gradient_clip(Some((Q16_16::from_int(-1), Q16_16::ONE)));
92
93    // ---- Training ----
94    let mut loss_csv = BufWriter::new(File::create(out_dir.join("energy_loss.csv"))?);
95    writeln!(loss_csv, "iter,avg_err")?;
96    let mut err_sum = 0.0;
97    for it in 0..ITERATIONS {
98        let s = &train[rng.next_i32() as usize % train.len()];
99        let input = to_input(s, &feat_stats);
100        let target = to_target(s, &target_stats);
101
102        nn.feed_forward(&input);
103        let err = nn.calculate_error(&target);
104        if !err.is_within_zero_tolerance() {
105            nn.train(&target);
106        }
107        err_sum += err.to_f64().abs();
108
109        if (it + 1) % REPORT_EVERY == 0 {
110            let avg = err_sum / f64::from(REPORT_EVERY);
111            writeln!(
112                stdout,
113                "iter {:>6}   avg|err| = {}",
114                it + 1,
115                fmt_fixed(avg, 4)
116            )?;
117            writeln!(loss_csv, "{},{}", it + 1, fmt_g(avg))?;
118            err_sum = 0.0;
119        }
120    }
121    loss_csv.flush()?;
122
123    // ---- Evaluation (real load units) ----
124    let mut pred = BufWriter::new(File::create(out_dir.join("energy_pred.csv"))?);
125    writeln!(pred, "sample,y1_true,y1_pred,y2_true,y2_pred")?;
126    let mut sum_abs = [0.0; 2];
127    let mut sum_sq_res = [0.0; 2];
128    let mut sum_true = [0.0; 2];
129    let mut sum_sq_true = [0.0; 2];
130    for (i, s) in test.iter().enumerate() {
131        nn.feed_forward(&to_input(s, &feat_stats));
132        let learned = nn.learned_values();
133        let mut y_pred = [0.0; 2];
134        for t in 0..2 {
135            y_pred[t] = from_target(learned[t].to_f64(), t, &target_stats);
136            let r = y_pred[t] - s.load[t];
137            sum_abs[t] += r.abs();
138            sum_sq_res[t] += r * r;
139            sum_true[t] += s.load[t];
140            sum_sq_true[t] += s.load[t] * s.load[t];
141        }
142        writeln!(
143            pred,
144            "{i},{},{},{},{}",
145            fmt_g(s.load[0]),
146            fmt_g(y_pred[0]),
147            fmt_g(s.load[1]),
148            fmt_g(y_pred[1])
149        )?;
150    }
151    pred.flush()?;
152
153    let n = test.len() as f64;
154    let mut mae = [0.0; 2];
155    let mut r2 = [0.0; 2];
156    for t in 0..2 {
157        mae[t] = sum_abs[t] / n;
158        let mean_true = sum_true[t] / n;
159        let ss_tot = sum_sq_true[t] - n * mean_true * mean_true;
160        r2[t] = if ss_tot > 1e-9 {
161            1.0 - sum_sq_res[t] / ss_tot
162        } else {
163            0.0
164        };
165    }
166    writeln!(
167        stdout,
168        "\nHeating load (Y1):  MAE={}  R2={}",
169        fmt_fixed(mae[0], 4),
170        fmt_fixed(r2[0], 4)
171    )?;
172    writeln!(
173        stdout,
174        "Cooling load (Y2):  MAE={}  R2={}",
175        fmt_fixed(mae[1], 4),
176        fmt_fixed(r2[1], 4)
177    )?;
178    stdout.flush()
179}
Source§

impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt> MultilayerPerceptron<V, H, O, IN, HID, OUT, Opt>
where V: Fixed, H: Activation<V>, O: Activation<V>, Opt: Optimizer<V>,

Source

pub fn with_optimizer(random_weight: impl FnMut() -> V, optimizer: Opt) -> Self

As new, trained with optimizer, for example Adam.

Source

pub fn set_learning_rate(&mut self, rate: V)

Replace the learning rate (default 2^-2, tinymind’s DefaultNetworkInitializer).

Examples found in repository?
examples/common/xor_driver.rs (line 127)
107fn run<V: Format>(
108    out_dir: &Path,
109    learning_rate: Option<f64>,
110    momentum: Option<f64>,
111    stdout: &mut dyn Write,
112) -> io::Result<()>
113where
114    Tanh: Activation<V>,
115    Sigmoid: Activation<V>,
116{
117    // The C++ example seeds rand() twice: srand(WEIGHT_INIT_SEED = 1), construct
118    // the network (which draws the initial weights), then srand(7) for the
119    // training samples. Re-seeding a global generator becomes two independent
120    // generator values in Rust. (The two seeds exist because the C++ network used
121    // to be a global, built before main() seeded rand(), i.e. from glibc's default
122    // seed of 1; tinymind PR #236 made that explicit without changing any output.)
123    let mut init_rng = GlibcRand::new(WEIGHT_INIT_SEED);
124    let mut nn = NeuralNetwork::<V>::new(|| V::random_weight(init_rng.next_i32()));
125    let mut rng = GlibcRand::new(RANDOM_SEED);
126    if let Some(lr) = learning_rate {
127        nn.set_learning_rate(V::from_f64_trunc(lr));
128    }
129    if let Some(m) = momentum {
130        nn.set_momentum_rate(V::from_f64_trunc(m));
131    }
132
133    let mut results = BufWriter::new(File::create(out_dir.join("nn_fixed_xor.txt"))?);
134    let mut curve = BufWriter::new(File::create(out_dir.join("xor_training.csv"))?);
135    writeln!(curve, "iteration,avg_error")?;
136
137    write_header(&mut results)?;
138
139    let mut avg_error = V::ZERO;
140    for i in 0..TRAINING_ITERATIONS {
141        let (inputs, target) = generate_xor_training_value::<V>(&mut rng);
142
143        nn.feed_forward(&inputs);
144        let error = nn.calculate_error(&target);
145        if !error.is_within_zero_tolerance() {
146            nn.train(&target);
147        }
148        let learned = nn.learned_values();
149
150        store_network_properties(&nn, &mut results, &target, &learned)?;
151        writeln!(results, "{error}")?;
152
153        // Accumulate |error| in raw LSBs; the average divides it back down.
154        avg_error += error.abs();
155        if (i + 1) % NUM_SAMPLES_AVG_ERROR == 0 {
156            avg_error = avg_error / V::from_int(NUM_SAMPLES_AVG_ERROR as i32);
157            writeln!(stdout, "Iteration: {} Average Error: {}", i + 1, avg_error)?;
158            writeln!(curve, "{},{}", i + 1, fmt_g(evaluate_xor_error(&mut nn)))?;
159            avg_error = V::ZERO;
160        }
161    }
162
163    // Success = every XOR pattern lands on the correct side of 0.5.
164    let mut correct = 0;
165    for [a, b, expected] in XOR_CASES {
166        let pred = predict(&mut nn, V::from_int(a), V::from_int(b));
167        let ok = (pred >= 0.5) == (expected == 1);
168        correct += u32::from(ok);
169        writeln!(
170            stdout,
171            "  {a} ^ {b} = {expected}  pred={}{}",
172            fmt_g(pred),
173            if ok { "  ok" } else { "  WRONG" }
174        )?;
175    }
176    writeln!(
177        stdout,
178        "{correct}/4 patterns classified correctly. Final 4-case error: {}",
179        fmt_g(evaluate_xor_error(&mut nn))
180    )?;
181
182    // Decision surface over the [0,1]^2 grid.
183    let mut surf = BufWriter::new(File::create(out_dir.join("xor_decision_surface.csv"))?);
184    writeln!(surf, "x0,x1,prob")?;
185    const G: i32 = 41;
186    for a in 0..G {
187        for b in 0..G {
188            let x0 = f64::from(a) / f64::from(G - 1);
189            let x1 = f64::from(b) / f64::from(G - 1);
190            let prob = predict(&mut nn, V::from_f64_trunc(x0), V::from_f64_trunc(x1));
191            writeln!(surf, "{},{},{}", fmt_g(x0), fmt_g(x1), fmt_g(prob))?;
192        }
193    }
194
195    // Flush explicitly so a write error is reported rather than lost in Drop.
196    results.flush()?;
197    curve.flush()?;
198    surf.flush()?;
199    stdout.flush()
200}
More examples
Hide additional examples
examples/common/energy_driver.rs (line 88)
58pub fn run(out_dir: &Path, data_path: &Path, stdout: &mut dyn Write) -> io::Result<()> {
59    // The C++ seeds rand() with WEIGHT_INIT_SEED, builds the network (drawing
60    // its weights), then re-seeds with 7. Two generators here.
61    let mut init_rng = GlibcRand::new(WEIGHT_INIT_SEED);
62    let mut nn = NeuralNetwork::new(|| random_weight(init_rng.next_i32()));
63
64    let Some(mut data) = load_csv(data_path) else {
65        return Err(io::Error::new(
66            io::ErrorKind::InvalidData,
67            format!("could not open or parse {}", data_path.display()),
68        ));
69    };
70    writeln!(stdout, "Loaded {} rows from ENB2012_data.csv.", data.len())?;
71
72    // Deterministic shuffle + 80/20 split.
73    let mut rng = GlibcRand::new(RANDOM_SEED);
74    for i in (2..=data.len()).rev() {
75        let j = rng.next_i32() as usize % i;
76        data.swap(i - 1, j);
77    }
78    let n_train = data.len() * 4 / 5;
79    let (train, test) = data.split_at(n_train);
80    writeln!(stdout, "Train: {}  Test: {}", train.len(), test.len())?;
81
82    let feat_stats = fit_stats(train, |s| s.feat);
83    let target_stats = fit_stats(train, |s| s.load);
84
85    // A modest learning rate, no momentum or acceleration, and gradients
86    // clipped to [-1, 1] (C++ GradientClipByValue<ValueType>): a linear output's
87    // unbounded gradient otherwise saturates Q16.16.
88    nn.set_learning_rate(to_q(0.02));
89    nn.set_momentum_rate(to_q(0.0));
90    nn.set_acceleration_rate(to_q(0.0));
91    nn.set_gradient_clip(Some((Q16_16::from_int(-1), Q16_16::ONE)));
92
93    // ---- Training ----
94    let mut loss_csv = BufWriter::new(File::create(out_dir.join("energy_loss.csv"))?);
95    writeln!(loss_csv, "iter,avg_err")?;
96    let mut err_sum = 0.0;
97    for it in 0..ITERATIONS {
98        let s = &train[rng.next_i32() as usize % train.len()];
99        let input = to_input(s, &feat_stats);
100        let target = to_target(s, &target_stats);
101
102        nn.feed_forward(&input);
103        let err = nn.calculate_error(&target);
104        if !err.is_within_zero_tolerance() {
105            nn.train(&target);
106        }
107        err_sum += err.to_f64().abs();
108
109        if (it + 1) % REPORT_EVERY == 0 {
110            let avg = err_sum / f64::from(REPORT_EVERY);
111            writeln!(
112                stdout,
113                "iter {:>6}   avg|err| = {}",
114                it + 1,
115                fmt_fixed(avg, 4)
116            )?;
117            writeln!(loss_csv, "{},{}", it + 1, fmt_g(avg))?;
118            err_sum = 0.0;
119        }
120    }
121    loss_csv.flush()?;
122
123    // ---- Evaluation (real load units) ----
124    let mut pred = BufWriter::new(File::create(out_dir.join("energy_pred.csv"))?);
125    writeln!(pred, "sample,y1_true,y1_pred,y2_true,y2_pred")?;
126    let mut sum_abs = [0.0; 2];
127    let mut sum_sq_res = [0.0; 2];
128    let mut sum_true = [0.0; 2];
129    let mut sum_sq_true = [0.0; 2];
130    for (i, s) in test.iter().enumerate() {
131        nn.feed_forward(&to_input(s, &feat_stats));
132        let learned = nn.learned_values();
133        let mut y_pred = [0.0; 2];
134        for t in 0..2 {
135            y_pred[t] = from_target(learned[t].to_f64(), t, &target_stats);
136            let r = y_pred[t] - s.load[t];
137            sum_abs[t] += r.abs();
138            sum_sq_res[t] += r * r;
139            sum_true[t] += s.load[t];
140            sum_sq_true[t] += s.load[t] * s.load[t];
141        }
142        writeln!(
143            pred,
144            "{i},{},{},{},{}",
145            fmt_g(s.load[0]),
146            fmt_g(y_pred[0]),
147            fmt_g(s.load[1]),
148            fmt_g(y_pred[1])
149        )?;
150    }
151    pred.flush()?;
152
153    let n = test.len() as f64;
154    let mut mae = [0.0; 2];
155    let mut r2 = [0.0; 2];
156    for t in 0..2 {
157        mae[t] = sum_abs[t] / n;
158        let mean_true = sum_true[t] / n;
159        let ss_tot = sum_sq_true[t] - n * mean_true * mean_true;
160        r2[t] = if ss_tot > 1e-9 {
161            1.0 - sum_sq_res[t] / ss_tot
162        } else {
163            0.0
164        };
165    }
166    writeln!(
167        stdout,
168        "\nHeating load (Y1):  MAE={}  R2={}",
169        fmt_fixed(mae[0], 4),
170        fmt_fixed(r2[0], 4)
171    )?;
172    writeln!(
173        stdout,
174        "Cooling load (Y2):  MAE={}  R2={}",
175        fmt_fixed(mae[1], 4),
176        fmt_fixed(r2[1], 4)
177    )?;
178    stdout.flush()
179}
Source

pub fn set_momentum_rate(&mut self, rate: V)

Replace the momentum rate (default 2^-1).

Examples found in repository?
examples/common/xor_driver.rs (line 130)
107fn run<V: Format>(
108    out_dir: &Path,
109    learning_rate: Option<f64>,
110    momentum: Option<f64>,
111    stdout: &mut dyn Write,
112) -> io::Result<()>
113where
114    Tanh: Activation<V>,
115    Sigmoid: Activation<V>,
116{
117    // The C++ example seeds rand() twice: srand(WEIGHT_INIT_SEED = 1), construct
118    // the network (which draws the initial weights), then srand(7) for the
119    // training samples. Re-seeding a global generator becomes two independent
120    // generator values in Rust. (The two seeds exist because the C++ network used
121    // to be a global, built before main() seeded rand(), i.e. from glibc's default
122    // seed of 1; tinymind PR #236 made that explicit without changing any output.)
123    let mut init_rng = GlibcRand::new(WEIGHT_INIT_SEED);
124    let mut nn = NeuralNetwork::<V>::new(|| V::random_weight(init_rng.next_i32()));
125    let mut rng = GlibcRand::new(RANDOM_SEED);
126    if let Some(lr) = learning_rate {
127        nn.set_learning_rate(V::from_f64_trunc(lr));
128    }
129    if let Some(m) = momentum {
130        nn.set_momentum_rate(V::from_f64_trunc(m));
131    }
132
133    let mut results = BufWriter::new(File::create(out_dir.join("nn_fixed_xor.txt"))?);
134    let mut curve = BufWriter::new(File::create(out_dir.join("xor_training.csv"))?);
135    writeln!(curve, "iteration,avg_error")?;
136
137    write_header(&mut results)?;
138
139    let mut avg_error = V::ZERO;
140    for i in 0..TRAINING_ITERATIONS {
141        let (inputs, target) = generate_xor_training_value::<V>(&mut rng);
142
143        nn.feed_forward(&inputs);
144        let error = nn.calculate_error(&target);
145        if !error.is_within_zero_tolerance() {
146            nn.train(&target);
147        }
148        let learned = nn.learned_values();
149
150        store_network_properties(&nn, &mut results, &target, &learned)?;
151        writeln!(results, "{error}")?;
152
153        // Accumulate |error| in raw LSBs; the average divides it back down.
154        avg_error += error.abs();
155        if (i + 1) % NUM_SAMPLES_AVG_ERROR == 0 {
156            avg_error = avg_error / V::from_int(NUM_SAMPLES_AVG_ERROR as i32);
157            writeln!(stdout, "Iteration: {} Average Error: {}", i + 1, avg_error)?;
158            writeln!(curve, "{},{}", i + 1, fmt_g(evaluate_xor_error(&mut nn)))?;
159            avg_error = V::ZERO;
160        }
161    }
162
163    // Success = every XOR pattern lands on the correct side of 0.5.
164    let mut correct = 0;
165    for [a, b, expected] in XOR_CASES {
166        let pred = predict(&mut nn, V::from_int(a), V::from_int(b));
167        let ok = (pred >= 0.5) == (expected == 1);
168        correct += u32::from(ok);
169        writeln!(
170            stdout,
171            "  {a} ^ {b} = {expected}  pred={}{}",
172            fmt_g(pred),
173            if ok { "  ok" } else { "  WRONG" }
174        )?;
175    }
176    writeln!(
177        stdout,
178        "{correct}/4 patterns classified correctly. Final 4-case error: {}",
179        fmt_g(evaluate_xor_error(&mut nn))
180    )?;
181
182    // Decision surface over the [0,1]^2 grid.
183    let mut surf = BufWriter::new(File::create(out_dir.join("xor_decision_surface.csv"))?);
184    writeln!(surf, "x0,x1,prob")?;
185    const G: i32 = 41;
186    for a in 0..G {
187        for b in 0..G {
188            let x0 = f64::from(a) / f64::from(G - 1);
189            let x1 = f64::from(b) / f64::from(G - 1);
190            let prob = predict(&mut nn, V::from_f64_trunc(x0), V::from_f64_trunc(x1));
191            writeln!(surf, "{},{},{}", fmt_g(x0), fmt_g(x1), fmt_g(prob))?;
192        }
193    }
194
195    // Flush explicitly so a write error is reported rather than lost in Drop.
196    results.flush()?;
197    curve.flush()?;
198    surf.flush()?;
199    stdout.flush()
200}
More examples
Hide additional examples
examples/common/energy_driver.rs (line 89)
58pub fn run(out_dir: &Path, data_path: &Path, stdout: &mut dyn Write) -> io::Result<()> {
59    // The C++ seeds rand() with WEIGHT_INIT_SEED, builds the network (drawing
60    // its weights), then re-seeds with 7. Two generators here.
61    let mut init_rng = GlibcRand::new(WEIGHT_INIT_SEED);
62    let mut nn = NeuralNetwork::new(|| random_weight(init_rng.next_i32()));
63
64    let Some(mut data) = load_csv(data_path) else {
65        return Err(io::Error::new(
66            io::ErrorKind::InvalidData,
67            format!("could not open or parse {}", data_path.display()),
68        ));
69    };
70    writeln!(stdout, "Loaded {} rows from ENB2012_data.csv.", data.len())?;
71
72    // Deterministic shuffle + 80/20 split.
73    let mut rng = GlibcRand::new(RANDOM_SEED);
74    for i in (2..=data.len()).rev() {
75        let j = rng.next_i32() as usize % i;
76        data.swap(i - 1, j);
77    }
78    let n_train = data.len() * 4 / 5;
79    let (train, test) = data.split_at(n_train);
80    writeln!(stdout, "Train: {}  Test: {}", train.len(), test.len())?;
81
82    let feat_stats = fit_stats(train, |s| s.feat);
83    let target_stats = fit_stats(train, |s| s.load);
84
85    // A modest learning rate, no momentum or acceleration, and gradients
86    // clipped to [-1, 1] (C++ GradientClipByValue<ValueType>): a linear output's
87    // unbounded gradient otherwise saturates Q16.16.
88    nn.set_learning_rate(to_q(0.02));
89    nn.set_momentum_rate(to_q(0.0));
90    nn.set_acceleration_rate(to_q(0.0));
91    nn.set_gradient_clip(Some((Q16_16::from_int(-1), Q16_16::ONE)));
92
93    // ---- Training ----
94    let mut loss_csv = BufWriter::new(File::create(out_dir.join("energy_loss.csv"))?);
95    writeln!(loss_csv, "iter,avg_err")?;
96    let mut err_sum = 0.0;
97    for it in 0..ITERATIONS {
98        let s = &train[rng.next_i32() as usize % train.len()];
99        let input = to_input(s, &feat_stats);
100        let target = to_target(s, &target_stats);
101
102        nn.feed_forward(&input);
103        let err = nn.calculate_error(&target);
104        if !err.is_within_zero_tolerance() {
105            nn.train(&target);
106        }
107        err_sum += err.to_f64().abs();
108
109        if (it + 1) % REPORT_EVERY == 0 {
110            let avg = err_sum / f64::from(REPORT_EVERY);
111            writeln!(
112                stdout,
113                "iter {:>6}   avg|err| = {}",
114                it + 1,
115                fmt_fixed(avg, 4)
116            )?;
117            writeln!(loss_csv, "{},{}", it + 1, fmt_g(avg))?;
118            err_sum = 0.0;
119        }
120    }
121    loss_csv.flush()?;
122
123    // ---- Evaluation (real load units) ----
124    let mut pred = BufWriter::new(File::create(out_dir.join("energy_pred.csv"))?);
125    writeln!(pred, "sample,y1_true,y1_pred,y2_true,y2_pred")?;
126    let mut sum_abs = [0.0; 2];
127    let mut sum_sq_res = [0.0; 2];
128    let mut sum_true = [0.0; 2];
129    let mut sum_sq_true = [0.0; 2];
130    for (i, s) in test.iter().enumerate() {
131        nn.feed_forward(&to_input(s, &feat_stats));
132        let learned = nn.learned_values();
133        let mut y_pred = [0.0; 2];
134        for t in 0..2 {
135            y_pred[t] = from_target(learned[t].to_f64(), t, &target_stats);
136            let r = y_pred[t] - s.load[t];
137            sum_abs[t] += r.abs();
138            sum_sq_res[t] += r * r;
139            sum_true[t] += s.load[t];
140            sum_sq_true[t] += s.load[t] * s.load[t];
141        }
142        writeln!(
143            pred,
144            "{i},{},{},{},{}",
145            fmt_g(s.load[0]),
146            fmt_g(y_pred[0]),
147            fmt_g(s.load[1]),
148            fmt_g(y_pred[1])
149        )?;
150    }
151    pred.flush()?;
152
153    let n = test.len() as f64;
154    let mut mae = [0.0; 2];
155    let mut r2 = [0.0; 2];
156    for t in 0..2 {
157        mae[t] = sum_abs[t] / n;
158        let mean_true = sum_true[t] / n;
159        let ss_tot = sum_sq_true[t] - n * mean_true * mean_true;
160        r2[t] = if ss_tot > 1e-9 {
161            1.0 - sum_sq_res[t] / ss_tot
162        } else {
163            0.0
164        };
165    }
166    writeln!(
167        stdout,
168        "\nHeating load (Y1):  MAE={}  R2={}",
169        fmt_fixed(mae[0], 4),
170        fmt_fixed(r2[0], 4)
171    )?;
172    writeln!(
173        stdout,
174        "Cooling load (Y2):  MAE={}  R2={}",
175        fmt_fixed(mae[1], 4),
176        fmt_fixed(r2[1], 4)
177    )?;
178    stdout.flush()
179}
Source

pub fn set_acceleration_rate(&mut self, rate: V)

Replace the acceleration rate, the weight on the delta weight from two steps back (default 2^-4).

Examples found in repository?
examples/common/energy_driver.rs (line 90)
58pub fn run(out_dir: &Path, data_path: &Path, stdout: &mut dyn Write) -> io::Result<()> {
59    // The C++ seeds rand() with WEIGHT_INIT_SEED, builds the network (drawing
60    // its weights), then re-seeds with 7. Two generators here.
61    let mut init_rng = GlibcRand::new(WEIGHT_INIT_SEED);
62    let mut nn = NeuralNetwork::new(|| random_weight(init_rng.next_i32()));
63
64    let Some(mut data) = load_csv(data_path) else {
65        return Err(io::Error::new(
66            io::ErrorKind::InvalidData,
67            format!("could not open or parse {}", data_path.display()),
68        ));
69    };
70    writeln!(stdout, "Loaded {} rows from ENB2012_data.csv.", data.len())?;
71
72    // Deterministic shuffle + 80/20 split.
73    let mut rng = GlibcRand::new(RANDOM_SEED);
74    for i in (2..=data.len()).rev() {
75        let j = rng.next_i32() as usize % i;
76        data.swap(i - 1, j);
77    }
78    let n_train = data.len() * 4 / 5;
79    let (train, test) = data.split_at(n_train);
80    writeln!(stdout, "Train: {}  Test: {}", train.len(), test.len())?;
81
82    let feat_stats = fit_stats(train, |s| s.feat);
83    let target_stats = fit_stats(train, |s| s.load);
84
85    // A modest learning rate, no momentum or acceleration, and gradients
86    // clipped to [-1, 1] (C++ GradientClipByValue<ValueType>): a linear output's
87    // unbounded gradient otherwise saturates Q16.16.
88    nn.set_learning_rate(to_q(0.02));
89    nn.set_momentum_rate(to_q(0.0));
90    nn.set_acceleration_rate(to_q(0.0));
91    nn.set_gradient_clip(Some((Q16_16::from_int(-1), Q16_16::ONE)));
92
93    // ---- Training ----
94    let mut loss_csv = BufWriter::new(File::create(out_dir.join("energy_loss.csv"))?);
95    writeln!(loss_csv, "iter,avg_err")?;
96    let mut err_sum = 0.0;
97    for it in 0..ITERATIONS {
98        let s = &train[rng.next_i32() as usize % train.len()];
99        let input = to_input(s, &feat_stats);
100        let target = to_target(s, &target_stats);
101
102        nn.feed_forward(&input);
103        let err = nn.calculate_error(&target);
104        if !err.is_within_zero_tolerance() {
105            nn.train(&target);
106        }
107        err_sum += err.to_f64().abs();
108
109        if (it + 1) % REPORT_EVERY == 0 {
110            let avg = err_sum / f64::from(REPORT_EVERY);
111            writeln!(
112                stdout,
113                "iter {:>6}   avg|err| = {}",
114                it + 1,
115                fmt_fixed(avg, 4)
116            )?;
117            writeln!(loss_csv, "{},{}", it + 1, fmt_g(avg))?;
118            err_sum = 0.0;
119        }
120    }
121    loss_csv.flush()?;
122
123    // ---- Evaluation (real load units) ----
124    let mut pred = BufWriter::new(File::create(out_dir.join("energy_pred.csv"))?);
125    writeln!(pred, "sample,y1_true,y1_pred,y2_true,y2_pred")?;
126    let mut sum_abs = [0.0; 2];
127    let mut sum_sq_res = [0.0; 2];
128    let mut sum_true = [0.0; 2];
129    let mut sum_sq_true = [0.0; 2];
130    for (i, s) in test.iter().enumerate() {
131        nn.feed_forward(&to_input(s, &feat_stats));
132        let learned = nn.learned_values();
133        let mut y_pred = [0.0; 2];
134        for t in 0..2 {
135            y_pred[t] = from_target(learned[t].to_f64(), t, &target_stats);
136            let r = y_pred[t] - s.load[t];
137            sum_abs[t] += r.abs();
138            sum_sq_res[t] += r * r;
139            sum_true[t] += s.load[t];
140            sum_sq_true[t] += s.load[t] * s.load[t];
141        }
142        writeln!(
143            pred,
144            "{i},{},{},{},{}",
145            fmt_g(s.load[0]),
146            fmt_g(y_pred[0]),
147            fmt_g(s.load[1]),
148            fmt_g(y_pred[1])
149        )?;
150    }
151    pred.flush()?;
152
153    let n = test.len() as f64;
154    let mut mae = [0.0; 2];
155    let mut r2 = [0.0; 2];
156    for t in 0..2 {
157        mae[t] = sum_abs[t] / n;
158        let mean_true = sum_true[t] / n;
159        let ss_tot = sum_sq_true[t] - n * mean_true * mean_true;
160        r2[t] = if ss_tot > 1e-9 {
161            1.0 - sum_sq_res[t] / ss_tot
162        } else {
163            0.0
164        };
165    }
166    writeln!(
167        stdout,
168        "\nHeating load (Y1):  MAE={}  R2={}",
169        fmt_fixed(mae[0], 4),
170        fmt_fixed(r2[0], 4)
171    )?;
172    writeln!(
173        stdout,
174        "Cooling load (Y2):  MAE={}  R2={}",
175        fmt_fixed(mae[1], 4),
176        fmt_fixed(r2[1], 4)
177    )?;
178    stdout.flush()
179}
Source

pub fn set_gradient_clip(&mut self, range: Option<(V, V)>)

Clip each weight’s gradient to [min, max] before the update, or None (the default) to leave gradients alone. C++ GradientClipByValue<ValueType, I, F> is Some((QValue(-I, F), QValue(I, F))), so the default GradientClipByValue<ValueType> is Some((-1.0, 1.0)). As in the C++, bias weights are never clipped.

Examples found in repository?
examples/common/energy_driver.rs (line 91)
58pub fn run(out_dir: &Path, data_path: &Path, stdout: &mut dyn Write) -> io::Result<()> {
59    // The C++ seeds rand() with WEIGHT_INIT_SEED, builds the network (drawing
60    // its weights), then re-seeds with 7. Two generators here.
61    let mut init_rng = GlibcRand::new(WEIGHT_INIT_SEED);
62    let mut nn = NeuralNetwork::new(|| random_weight(init_rng.next_i32()));
63
64    let Some(mut data) = load_csv(data_path) else {
65        return Err(io::Error::new(
66            io::ErrorKind::InvalidData,
67            format!("could not open or parse {}", data_path.display()),
68        ));
69    };
70    writeln!(stdout, "Loaded {} rows from ENB2012_data.csv.", data.len())?;
71
72    // Deterministic shuffle + 80/20 split.
73    let mut rng = GlibcRand::new(RANDOM_SEED);
74    for i in (2..=data.len()).rev() {
75        let j = rng.next_i32() as usize % i;
76        data.swap(i - 1, j);
77    }
78    let n_train = data.len() * 4 / 5;
79    let (train, test) = data.split_at(n_train);
80    writeln!(stdout, "Train: {}  Test: {}", train.len(), test.len())?;
81
82    let feat_stats = fit_stats(train, |s| s.feat);
83    let target_stats = fit_stats(train, |s| s.load);
84
85    // A modest learning rate, no momentum or acceleration, and gradients
86    // clipped to [-1, 1] (C++ GradientClipByValue<ValueType>): a linear output's
87    // unbounded gradient otherwise saturates Q16.16.
88    nn.set_learning_rate(to_q(0.02));
89    nn.set_momentum_rate(to_q(0.0));
90    nn.set_acceleration_rate(to_q(0.0));
91    nn.set_gradient_clip(Some((Q16_16::from_int(-1), Q16_16::ONE)));
92
93    // ---- Training ----
94    let mut loss_csv = BufWriter::new(File::create(out_dir.join("energy_loss.csv"))?);
95    writeln!(loss_csv, "iter,avg_err")?;
96    let mut err_sum = 0.0;
97    for it in 0..ITERATIONS {
98        let s = &train[rng.next_i32() as usize % train.len()];
99        let input = to_input(s, &feat_stats);
100        let target = to_target(s, &target_stats);
101
102        nn.feed_forward(&input);
103        let err = nn.calculate_error(&target);
104        if !err.is_within_zero_tolerance() {
105            nn.train(&target);
106        }
107        err_sum += err.to_f64().abs();
108
109        if (it + 1) % REPORT_EVERY == 0 {
110            let avg = err_sum / f64::from(REPORT_EVERY);
111            writeln!(
112                stdout,
113                "iter {:>6}   avg|err| = {}",
114                it + 1,
115                fmt_fixed(avg, 4)
116            )?;
117            writeln!(loss_csv, "{},{}", it + 1, fmt_g(avg))?;
118            err_sum = 0.0;
119        }
120    }
121    loss_csv.flush()?;
122
123    // ---- Evaluation (real load units) ----
124    let mut pred = BufWriter::new(File::create(out_dir.join("energy_pred.csv"))?);
125    writeln!(pred, "sample,y1_true,y1_pred,y2_true,y2_pred")?;
126    let mut sum_abs = [0.0; 2];
127    let mut sum_sq_res = [0.0; 2];
128    let mut sum_true = [0.0; 2];
129    let mut sum_sq_true = [0.0; 2];
130    for (i, s) in test.iter().enumerate() {
131        nn.feed_forward(&to_input(s, &feat_stats));
132        let learned = nn.learned_values();
133        let mut y_pred = [0.0; 2];
134        for t in 0..2 {
135            y_pred[t] = from_target(learned[t].to_f64(), t, &target_stats);
136            let r = y_pred[t] - s.load[t];
137            sum_abs[t] += r.abs();
138            sum_sq_res[t] += r * r;
139            sum_true[t] += s.load[t];
140            sum_sq_true[t] += s.load[t] * s.load[t];
141        }
142        writeln!(
143            pred,
144            "{i},{},{},{},{}",
145            fmt_g(s.load[0]),
146            fmt_g(y_pred[0]),
147            fmt_g(s.load[1]),
148            fmt_g(y_pred[1])
149        )?;
150    }
151    pred.flush()?;
152
153    let n = test.len() as f64;
154    let mut mae = [0.0; 2];
155    let mut r2 = [0.0; 2];
156    for t in 0..2 {
157        mae[t] = sum_abs[t] / n;
158        let mean_true = sum_true[t] / n;
159        let ss_tot = sum_sq_true[t] - n * mean_true * mean_true;
160        r2[t] = if ss_tot > 1e-9 {
161            1.0 - sum_sq_res[t] / ss_tot
162        } else {
163            0.0
164        };
165    }
166    writeln!(
167        stdout,
168        "\nHeating load (Y1):  MAE={}  R2={}",
169        fmt_fixed(mae[0], 4),
170        fmt_fixed(r2[0], 4)
171    )?;
172    writeln!(
173        stdout,
174        "Cooling load (Y2):  MAE={}  R2={}",
175        fmt_fixed(mae[1], 4),
176        fmt_fixed(r2[1], 4)
177    )?;
178    stdout.flush()
179}
Source

pub fn feed_forward(&mut self, inputs: &[V; IN])

Run one forward pass: load inputs, then compute the hidden and output activations. Read the result with learned_values.

Examples found in repository?
examples/common/xor_driver.rs (line 143)
107fn run<V: Format>(
108    out_dir: &Path,
109    learning_rate: Option<f64>,
110    momentum: Option<f64>,
111    stdout: &mut dyn Write,
112) -> io::Result<()>
113where
114    Tanh: Activation<V>,
115    Sigmoid: Activation<V>,
116{
117    // The C++ example seeds rand() twice: srand(WEIGHT_INIT_SEED = 1), construct
118    // the network (which draws the initial weights), then srand(7) for the
119    // training samples. Re-seeding a global generator becomes two independent
120    // generator values in Rust. (The two seeds exist because the C++ network used
121    // to be a global, built before main() seeded rand(), i.e. from glibc's default
122    // seed of 1; tinymind PR #236 made that explicit without changing any output.)
123    let mut init_rng = GlibcRand::new(WEIGHT_INIT_SEED);
124    let mut nn = NeuralNetwork::<V>::new(|| V::random_weight(init_rng.next_i32()));
125    let mut rng = GlibcRand::new(RANDOM_SEED);
126    if let Some(lr) = learning_rate {
127        nn.set_learning_rate(V::from_f64_trunc(lr));
128    }
129    if let Some(m) = momentum {
130        nn.set_momentum_rate(V::from_f64_trunc(m));
131    }
132
133    let mut results = BufWriter::new(File::create(out_dir.join("nn_fixed_xor.txt"))?);
134    let mut curve = BufWriter::new(File::create(out_dir.join("xor_training.csv"))?);
135    writeln!(curve, "iteration,avg_error")?;
136
137    write_header(&mut results)?;
138
139    let mut avg_error = V::ZERO;
140    for i in 0..TRAINING_ITERATIONS {
141        let (inputs, target) = generate_xor_training_value::<V>(&mut rng);
142
143        nn.feed_forward(&inputs);
144        let error = nn.calculate_error(&target);
145        if !error.is_within_zero_tolerance() {
146            nn.train(&target);
147        }
148        let learned = nn.learned_values();
149
150        store_network_properties(&nn, &mut results, &target, &learned)?;
151        writeln!(results, "{error}")?;
152
153        // Accumulate |error| in raw LSBs; the average divides it back down.
154        avg_error += error.abs();
155        if (i + 1) % NUM_SAMPLES_AVG_ERROR == 0 {
156            avg_error = avg_error / V::from_int(NUM_SAMPLES_AVG_ERROR as i32);
157            writeln!(stdout, "Iteration: {} Average Error: {}", i + 1, avg_error)?;
158            writeln!(curve, "{},{}", i + 1, fmt_g(evaluate_xor_error(&mut nn)))?;
159            avg_error = V::ZERO;
160        }
161    }
162
163    // Success = every XOR pattern lands on the correct side of 0.5.
164    let mut correct = 0;
165    for [a, b, expected] in XOR_CASES {
166        let pred = predict(&mut nn, V::from_int(a), V::from_int(b));
167        let ok = (pred >= 0.5) == (expected == 1);
168        correct += u32::from(ok);
169        writeln!(
170            stdout,
171            "  {a} ^ {b} = {expected}  pred={}{}",
172            fmt_g(pred),
173            if ok { "  ok" } else { "  WRONG" }
174        )?;
175    }
176    writeln!(
177        stdout,
178        "{correct}/4 patterns classified correctly. Final 4-case error: {}",
179        fmt_g(evaluate_xor_error(&mut nn))
180    )?;
181
182    // Decision surface over the [0,1]^2 grid.
183    let mut surf = BufWriter::new(File::create(out_dir.join("xor_decision_surface.csv"))?);
184    writeln!(surf, "x0,x1,prob")?;
185    const G: i32 = 41;
186    for a in 0..G {
187        for b in 0..G {
188            let x0 = f64::from(a) / f64::from(G - 1);
189            let x1 = f64::from(b) / f64::from(G - 1);
190            let prob = predict(&mut nn, V::from_f64_trunc(x0), V::from_f64_trunc(x1));
191            writeln!(surf, "{},{},{}", fmt_g(x0), fmt_g(x1), fmt_g(prob))?;
192        }
193    }
194
195    // Flush explicitly so a write error is reported rather than lost in Drop.
196    results.flush()?;
197    curve.flush()?;
198    surf.flush()?;
199    stdout.flush()
200}
201
202fn generate_xor_training_value<V: Format>(rng: &mut GlibcRand) -> ([V; 2], [V; 1]) {
203    let x = rng.next_i32() & 1;
204    let y = rng.next_i32() & 1;
205    ([V::from_int(x), V::from_int(y)], [V::from_int(x ^ y)])
206}
207
208fn predict<V: Format>(nn: &mut NeuralNetwork<V>, x0: V, x1: V) -> f64
209where
210    Tanh: Activation<V>,
211    Sigmoid: Activation<V>,
212{
213    nn.feed_forward(&[x0, x1]);
214    nn.learned_values()[0].to_f64()
215}
More examples
Hide additional examples
examples/common/iris_driver.rs (line 90)
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}
examples/common/energy_driver.rs (line 102)
58pub fn run(out_dir: &Path, data_path: &Path, stdout: &mut dyn Write) -> io::Result<()> {
59    // The C++ seeds rand() with WEIGHT_INIT_SEED, builds the network (drawing
60    // its weights), then re-seeds with 7. Two generators here.
61    let mut init_rng = GlibcRand::new(WEIGHT_INIT_SEED);
62    let mut nn = NeuralNetwork::new(|| random_weight(init_rng.next_i32()));
63
64    let Some(mut data) = load_csv(data_path) else {
65        return Err(io::Error::new(
66            io::ErrorKind::InvalidData,
67            format!("could not open or parse {}", data_path.display()),
68        ));
69    };
70    writeln!(stdout, "Loaded {} rows from ENB2012_data.csv.", data.len())?;
71
72    // Deterministic shuffle + 80/20 split.
73    let mut rng = GlibcRand::new(RANDOM_SEED);
74    for i in (2..=data.len()).rev() {
75        let j = rng.next_i32() as usize % i;
76        data.swap(i - 1, j);
77    }
78    let n_train = data.len() * 4 / 5;
79    let (train, test) = data.split_at(n_train);
80    writeln!(stdout, "Train: {}  Test: {}", train.len(), test.len())?;
81
82    let feat_stats = fit_stats(train, |s| s.feat);
83    let target_stats = fit_stats(train, |s| s.load);
84
85    // A modest learning rate, no momentum or acceleration, and gradients
86    // clipped to [-1, 1] (C++ GradientClipByValue<ValueType>): a linear output's
87    // unbounded gradient otherwise saturates Q16.16.
88    nn.set_learning_rate(to_q(0.02));
89    nn.set_momentum_rate(to_q(0.0));
90    nn.set_acceleration_rate(to_q(0.0));
91    nn.set_gradient_clip(Some((Q16_16::from_int(-1), Q16_16::ONE)));
92
93    // ---- Training ----
94    let mut loss_csv = BufWriter::new(File::create(out_dir.join("energy_loss.csv"))?);
95    writeln!(loss_csv, "iter,avg_err")?;
96    let mut err_sum = 0.0;
97    for it in 0..ITERATIONS {
98        let s = &train[rng.next_i32() as usize % train.len()];
99        let input = to_input(s, &feat_stats);
100        let target = to_target(s, &target_stats);
101
102        nn.feed_forward(&input);
103        let err = nn.calculate_error(&target);
104        if !err.is_within_zero_tolerance() {
105            nn.train(&target);
106        }
107        err_sum += err.to_f64().abs();
108
109        if (it + 1) % REPORT_EVERY == 0 {
110            let avg = err_sum / f64::from(REPORT_EVERY);
111            writeln!(
112                stdout,
113                "iter {:>6}   avg|err| = {}",
114                it + 1,
115                fmt_fixed(avg, 4)
116            )?;
117            writeln!(loss_csv, "{},{}", it + 1, fmt_g(avg))?;
118            err_sum = 0.0;
119        }
120    }
121    loss_csv.flush()?;
122
123    // ---- Evaluation (real load units) ----
124    let mut pred = BufWriter::new(File::create(out_dir.join("energy_pred.csv"))?);
125    writeln!(pred, "sample,y1_true,y1_pred,y2_true,y2_pred")?;
126    let mut sum_abs = [0.0; 2];
127    let mut sum_sq_res = [0.0; 2];
128    let mut sum_true = [0.0; 2];
129    let mut sum_sq_true = [0.0; 2];
130    for (i, s) in test.iter().enumerate() {
131        nn.feed_forward(&to_input(s, &feat_stats));
132        let learned = nn.learned_values();
133        let mut y_pred = [0.0; 2];
134        for t in 0..2 {
135            y_pred[t] = from_target(learned[t].to_f64(), t, &target_stats);
136            let r = y_pred[t] - s.load[t];
137            sum_abs[t] += r.abs();
138            sum_sq_res[t] += r * r;
139            sum_true[t] += s.load[t];
140            sum_sq_true[t] += s.load[t] * s.load[t];
141        }
142        writeln!(
143            pred,
144            "{i},{},{},{},{}",
145            fmt_g(s.load[0]),
146            fmt_g(y_pred[0]),
147            fmt_g(s.load[1]),
148            fmt_g(y_pred[1])
149        )?;
150    }
151    pred.flush()?;
152
153    let n = test.len() as f64;
154    let mut mae = [0.0; 2];
155    let mut r2 = [0.0; 2];
156    for t in 0..2 {
157        mae[t] = sum_abs[t] / n;
158        let mean_true = sum_true[t] / n;
159        let ss_tot = sum_sq_true[t] - n * mean_true * mean_true;
160        r2[t] = if ss_tot > 1e-9 {
161            1.0 - sum_sq_res[t] / ss_tot
162        } else {
163            0.0
164        };
165    }
166    writeln!(
167        stdout,
168        "\nHeating load (Y1):  MAE={}  R2={}",
169        fmt_fixed(mae[0], 4),
170        fmt_fixed(r2[0], 4)
171    )?;
172    writeln!(
173        stdout,
174        "Cooling load (Y2):  MAE={}  R2={}",
175        fmt_fixed(mae[1], 4),
176        fmt_fixed(r2[1], 4)
177    )?;
178    stdout.flush()
179}
Source

pub fn learned_values(&self) -> [V; OUT]

The output-layer activations from the latest feed_forward.

Examples found in repository?
examples/common/xor_driver.rs (line 148)
107fn run<V: Format>(
108    out_dir: &Path,
109    learning_rate: Option<f64>,
110    momentum: Option<f64>,
111    stdout: &mut dyn Write,
112) -> io::Result<()>
113where
114    Tanh: Activation<V>,
115    Sigmoid: Activation<V>,
116{
117    // The C++ example seeds rand() twice: srand(WEIGHT_INIT_SEED = 1), construct
118    // the network (which draws the initial weights), then srand(7) for the
119    // training samples. Re-seeding a global generator becomes two independent
120    // generator values in Rust. (The two seeds exist because the C++ network used
121    // to be a global, built before main() seeded rand(), i.e. from glibc's default
122    // seed of 1; tinymind PR #236 made that explicit without changing any output.)
123    let mut init_rng = GlibcRand::new(WEIGHT_INIT_SEED);
124    let mut nn = NeuralNetwork::<V>::new(|| V::random_weight(init_rng.next_i32()));
125    let mut rng = GlibcRand::new(RANDOM_SEED);
126    if let Some(lr) = learning_rate {
127        nn.set_learning_rate(V::from_f64_trunc(lr));
128    }
129    if let Some(m) = momentum {
130        nn.set_momentum_rate(V::from_f64_trunc(m));
131    }
132
133    let mut results = BufWriter::new(File::create(out_dir.join("nn_fixed_xor.txt"))?);
134    let mut curve = BufWriter::new(File::create(out_dir.join("xor_training.csv"))?);
135    writeln!(curve, "iteration,avg_error")?;
136
137    write_header(&mut results)?;
138
139    let mut avg_error = V::ZERO;
140    for i in 0..TRAINING_ITERATIONS {
141        let (inputs, target) = generate_xor_training_value::<V>(&mut rng);
142
143        nn.feed_forward(&inputs);
144        let error = nn.calculate_error(&target);
145        if !error.is_within_zero_tolerance() {
146            nn.train(&target);
147        }
148        let learned = nn.learned_values();
149
150        store_network_properties(&nn, &mut results, &target, &learned)?;
151        writeln!(results, "{error}")?;
152
153        // Accumulate |error| in raw LSBs; the average divides it back down.
154        avg_error += error.abs();
155        if (i + 1) % NUM_SAMPLES_AVG_ERROR == 0 {
156            avg_error = avg_error / V::from_int(NUM_SAMPLES_AVG_ERROR as i32);
157            writeln!(stdout, "Iteration: {} Average Error: {}", i + 1, avg_error)?;
158            writeln!(curve, "{},{}", i + 1, fmt_g(evaluate_xor_error(&mut nn)))?;
159            avg_error = V::ZERO;
160        }
161    }
162
163    // Success = every XOR pattern lands on the correct side of 0.5.
164    let mut correct = 0;
165    for [a, b, expected] in XOR_CASES {
166        let pred = predict(&mut nn, V::from_int(a), V::from_int(b));
167        let ok = (pred >= 0.5) == (expected == 1);
168        correct += u32::from(ok);
169        writeln!(
170            stdout,
171            "  {a} ^ {b} = {expected}  pred={}{}",
172            fmt_g(pred),
173            if ok { "  ok" } else { "  WRONG" }
174        )?;
175    }
176    writeln!(
177        stdout,
178        "{correct}/4 patterns classified correctly. Final 4-case error: {}",
179        fmt_g(evaluate_xor_error(&mut nn))
180    )?;
181
182    // Decision surface over the [0,1]^2 grid.
183    let mut surf = BufWriter::new(File::create(out_dir.join("xor_decision_surface.csv"))?);
184    writeln!(surf, "x0,x1,prob")?;
185    const G: i32 = 41;
186    for a in 0..G {
187        for b in 0..G {
188            let x0 = f64::from(a) / f64::from(G - 1);
189            let x1 = f64::from(b) / f64::from(G - 1);
190            let prob = predict(&mut nn, V::from_f64_trunc(x0), V::from_f64_trunc(x1));
191            writeln!(surf, "{},{},{}", fmt_g(x0), fmt_g(x1), fmt_g(prob))?;
192        }
193    }
194
195    // Flush explicitly so a write error is reported rather than lost in Drop.
196    results.flush()?;
197    curve.flush()?;
198    surf.flush()?;
199    stdout.flush()
200}
201
202fn generate_xor_training_value<V: Format>(rng: &mut GlibcRand) -> ([V; 2], [V; 1]) {
203    let x = rng.next_i32() & 1;
204    let y = rng.next_i32() & 1;
205    ([V::from_int(x), V::from_int(y)], [V::from_int(x ^ y)])
206}
207
208fn predict<V: Format>(nn: &mut NeuralNetwork<V>, x0: V, x1: V) -> f64
209where
210    Tanh: Activation<V>,
211    Sigmoid: Activation<V>,
212{
213    nn.feed_forward(&[x0, x1]);
214    nn.learned_values()[0].to_f64()
215}
More examples
Hide additional examples
examples/common/iris_driver.rs (line 118)
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}
examples/common/energy_driver.rs (line 132)
58pub fn run(out_dir: &Path, data_path: &Path, stdout: &mut dyn Write) -> io::Result<()> {
59    // The C++ seeds rand() with WEIGHT_INIT_SEED, builds the network (drawing
60    // its weights), then re-seeds with 7. Two generators here.
61    let mut init_rng = GlibcRand::new(WEIGHT_INIT_SEED);
62    let mut nn = NeuralNetwork::new(|| random_weight(init_rng.next_i32()));
63
64    let Some(mut data) = load_csv(data_path) else {
65        return Err(io::Error::new(
66            io::ErrorKind::InvalidData,
67            format!("could not open or parse {}", data_path.display()),
68        ));
69    };
70    writeln!(stdout, "Loaded {} rows from ENB2012_data.csv.", data.len())?;
71
72    // Deterministic shuffle + 80/20 split.
73    let mut rng = GlibcRand::new(RANDOM_SEED);
74    for i in (2..=data.len()).rev() {
75        let j = rng.next_i32() as usize % i;
76        data.swap(i - 1, j);
77    }
78    let n_train = data.len() * 4 / 5;
79    let (train, test) = data.split_at(n_train);
80    writeln!(stdout, "Train: {}  Test: {}", train.len(), test.len())?;
81
82    let feat_stats = fit_stats(train, |s| s.feat);
83    let target_stats = fit_stats(train, |s| s.load);
84
85    // A modest learning rate, no momentum or acceleration, and gradients
86    // clipped to [-1, 1] (C++ GradientClipByValue<ValueType>): a linear output's
87    // unbounded gradient otherwise saturates Q16.16.
88    nn.set_learning_rate(to_q(0.02));
89    nn.set_momentum_rate(to_q(0.0));
90    nn.set_acceleration_rate(to_q(0.0));
91    nn.set_gradient_clip(Some((Q16_16::from_int(-1), Q16_16::ONE)));
92
93    // ---- Training ----
94    let mut loss_csv = BufWriter::new(File::create(out_dir.join("energy_loss.csv"))?);
95    writeln!(loss_csv, "iter,avg_err")?;
96    let mut err_sum = 0.0;
97    for it in 0..ITERATIONS {
98        let s = &train[rng.next_i32() as usize % train.len()];
99        let input = to_input(s, &feat_stats);
100        let target = to_target(s, &target_stats);
101
102        nn.feed_forward(&input);
103        let err = nn.calculate_error(&target);
104        if !err.is_within_zero_tolerance() {
105            nn.train(&target);
106        }
107        err_sum += err.to_f64().abs();
108
109        if (it + 1) % REPORT_EVERY == 0 {
110            let avg = err_sum / f64::from(REPORT_EVERY);
111            writeln!(
112                stdout,
113                "iter {:>6}   avg|err| = {}",
114                it + 1,
115                fmt_fixed(avg, 4)
116            )?;
117            writeln!(loss_csv, "{},{}", it + 1, fmt_g(avg))?;
118            err_sum = 0.0;
119        }
120    }
121    loss_csv.flush()?;
122
123    // ---- Evaluation (real load units) ----
124    let mut pred = BufWriter::new(File::create(out_dir.join("energy_pred.csv"))?);
125    writeln!(pred, "sample,y1_true,y1_pred,y2_true,y2_pred")?;
126    let mut sum_abs = [0.0; 2];
127    let mut sum_sq_res = [0.0; 2];
128    let mut sum_true = [0.0; 2];
129    let mut sum_sq_true = [0.0; 2];
130    for (i, s) in test.iter().enumerate() {
131        nn.feed_forward(&to_input(s, &feat_stats));
132        let learned = nn.learned_values();
133        let mut y_pred = [0.0; 2];
134        for t in 0..2 {
135            y_pred[t] = from_target(learned[t].to_f64(), t, &target_stats);
136            let r = y_pred[t] - s.load[t];
137            sum_abs[t] += r.abs();
138            sum_sq_res[t] += r * r;
139            sum_true[t] += s.load[t];
140            sum_sq_true[t] += s.load[t] * s.load[t];
141        }
142        writeln!(
143            pred,
144            "{i},{},{},{},{}",
145            fmt_g(s.load[0]),
146            fmt_g(y_pred[0]),
147            fmt_g(s.load[1]),
148            fmt_g(y_pred[1])
149        )?;
150    }
151    pred.flush()?;
152
153    let n = test.len() as f64;
154    let mut mae = [0.0; 2];
155    let mut r2 = [0.0; 2];
156    for t in 0..2 {
157        mae[t] = sum_abs[t] / n;
158        let mean_true = sum_true[t] / n;
159        let ss_tot = sum_sq_true[t] - n * mean_true * mean_true;
160        r2[t] = if ss_tot > 1e-9 {
161            1.0 - sum_sq_res[t] / ss_tot
162        } else {
163            0.0
164        };
165    }
166    writeln!(
167        stdout,
168        "\nHeating load (Y1):  MAE={}  R2={}",
169        fmt_fixed(mae[0], 4),
170        fmt_fixed(r2[0], 4)
171    )?;
172    writeln!(
173        stdout,
174        "Cooling load (Y2):  MAE={}  R2={}",
175        fmt_fixed(mae[1], 4),
176        fmt_fixed(r2[1], 4)
177    )?;
178    stdout.flush()
179}
Source

pub fn calculate_error(&self, targets: &[V; OUT]) -> V

Mean-squared error against targets (C++ MeanSquaredErrorCalculator).

Examples found in repository?
examples/common/xor_driver.rs (line 144)
107fn run<V: Format>(
108    out_dir: &Path,
109    learning_rate: Option<f64>,
110    momentum: Option<f64>,
111    stdout: &mut dyn Write,
112) -> io::Result<()>
113where
114    Tanh: Activation<V>,
115    Sigmoid: Activation<V>,
116{
117    // The C++ example seeds rand() twice: srand(WEIGHT_INIT_SEED = 1), construct
118    // the network (which draws the initial weights), then srand(7) for the
119    // training samples. Re-seeding a global generator becomes two independent
120    // generator values in Rust. (The two seeds exist because the C++ network used
121    // to be a global, built before main() seeded rand(), i.e. from glibc's default
122    // seed of 1; tinymind PR #236 made that explicit without changing any output.)
123    let mut init_rng = GlibcRand::new(WEIGHT_INIT_SEED);
124    let mut nn = NeuralNetwork::<V>::new(|| V::random_weight(init_rng.next_i32()));
125    let mut rng = GlibcRand::new(RANDOM_SEED);
126    if let Some(lr) = learning_rate {
127        nn.set_learning_rate(V::from_f64_trunc(lr));
128    }
129    if let Some(m) = momentum {
130        nn.set_momentum_rate(V::from_f64_trunc(m));
131    }
132
133    let mut results = BufWriter::new(File::create(out_dir.join("nn_fixed_xor.txt"))?);
134    let mut curve = BufWriter::new(File::create(out_dir.join("xor_training.csv"))?);
135    writeln!(curve, "iteration,avg_error")?;
136
137    write_header(&mut results)?;
138
139    let mut avg_error = V::ZERO;
140    for i in 0..TRAINING_ITERATIONS {
141        let (inputs, target) = generate_xor_training_value::<V>(&mut rng);
142
143        nn.feed_forward(&inputs);
144        let error = nn.calculate_error(&target);
145        if !error.is_within_zero_tolerance() {
146            nn.train(&target);
147        }
148        let learned = nn.learned_values();
149
150        store_network_properties(&nn, &mut results, &target, &learned)?;
151        writeln!(results, "{error}")?;
152
153        // Accumulate |error| in raw LSBs; the average divides it back down.
154        avg_error += error.abs();
155        if (i + 1) % NUM_SAMPLES_AVG_ERROR == 0 {
156            avg_error = avg_error / V::from_int(NUM_SAMPLES_AVG_ERROR as i32);
157            writeln!(stdout, "Iteration: {} Average Error: {}", i + 1, avg_error)?;
158            writeln!(curve, "{},{}", i + 1, fmt_g(evaluate_xor_error(&mut nn)))?;
159            avg_error = V::ZERO;
160        }
161    }
162
163    // Success = every XOR pattern lands on the correct side of 0.5.
164    let mut correct = 0;
165    for [a, b, expected] in XOR_CASES {
166        let pred = predict(&mut nn, V::from_int(a), V::from_int(b));
167        let ok = (pred >= 0.5) == (expected == 1);
168        correct += u32::from(ok);
169        writeln!(
170            stdout,
171            "  {a} ^ {b} = {expected}  pred={}{}",
172            fmt_g(pred),
173            if ok { "  ok" } else { "  WRONG" }
174        )?;
175    }
176    writeln!(
177        stdout,
178        "{correct}/4 patterns classified correctly. Final 4-case error: {}",
179        fmt_g(evaluate_xor_error(&mut nn))
180    )?;
181
182    // Decision surface over the [0,1]^2 grid.
183    let mut surf = BufWriter::new(File::create(out_dir.join("xor_decision_surface.csv"))?);
184    writeln!(surf, "x0,x1,prob")?;
185    const G: i32 = 41;
186    for a in 0..G {
187        for b in 0..G {
188            let x0 = f64::from(a) / f64::from(G - 1);
189            let x1 = f64::from(b) / f64::from(G - 1);
190            let prob = predict(&mut nn, V::from_f64_trunc(x0), V::from_f64_trunc(x1));
191            writeln!(surf, "{},{},{}", fmt_g(x0), fmt_g(x1), fmt_g(prob))?;
192        }
193    }
194
195    // Flush explicitly so a write error is reported rather than lost in Drop.
196    results.flush()?;
197    curve.flush()?;
198    surf.flush()?;
199    stdout.flush()
200}
More examples
Hide additional examples
examples/common/iris_driver.rs (line 91)
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}
examples/common/energy_driver.rs (line 103)
58pub fn run(out_dir: &Path, data_path: &Path, stdout: &mut dyn Write) -> io::Result<()> {
59    // The C++ seeds rand() with WEIGHT_INIT_SEED, builds the network (drawing
60    // its weights), then re-seeds with 7. Two generators here.
61    let mut init_rng = GlibcRand::new(WEIGHT_INIT_SEED);
62    let mut nn = NeuralNetwork::new(|| random_weight(init_rng.next_i32()));
63
64    let Some(mut data) = load_csv(data_path) else {
65        return Err(io::Error::new(
66            io::ErrorKind::InvalidData,
67            format!("could not open or parse {}", data_path.display()),
68        ));
69    };
70    writeln!(stdout, "Loaded {} rows from ENB2012_data.csv.", data.len())?;
71
72    // Deterministic shuffle + 80/20 split.
73    let mut rng = GlibcRand::new(RANDOM_SEED);
74    for i in (2..=data.len()).rev() {
75        let j = rng.next_i32() as usize % i;
76        data.swap(i - 1, j);
77    }
78    let n_train = data.len() * 4 / 5;
79    let (train, test) = data.split_at(n_train);
80    writeln!(stdout, "Train: {}  Test: {}", train.len(), test.len())?;
81
82    let feat_stats = fit_stats(train, |s| s.feat);
83    let target_stats = fit_stats(train, |s| s.load);
84
85    // A modest learning rate, no momentum or acceleration, and gradients
86    // clipped to [-1, 1] (C++ GradientClipByValue<ValueType>): a linear output's
87    // unbounded gradient otherwise saturates Q16.16.
88    nn.set_learning_rate(to_q(0.02));
89    nn.set_momentum_rate(to_q(0.0));
90    nn.set_acceleration_rate(to_q(0.0));
91    nn.set_gradient_clip(Some((Q16_16::from_int(-1), Q16_16::ONE)));
92
93    // ---- Training ----
94    let mut loss_csv = BufWriter::new(File::create(out_dir.join("energy_loss.csv"))?);
95    writeln!(loss_csv, "iter,avg_err")?;
96    let mut err_sum = 0.0;
97    for it in 0..ITERATIONS {
98        let s = &train[rng.next_i32() as usize % train.len()];
99        let input = to_input(s, &feat_stats);
100        let target = to_target(s, &target_stats);
101
102        nn.feed_forward(&input);
103        let err = nn.calculate_error(&target);
104        if !err.is_within_zero_tolerance() {
105            nn.train(&target);
106        }
107        err_sum += err.to_f64().abs();
108
109        if (it + 1) % REPORT_EVERY == 0 {
110            let avg = err_sum / f64::from(REPORT_EVERY);
111            writeln!(
112                stdout,
113                "iter {:>6}   avg|err| = {}",
114                it + 1,
115                fmt_fixed(avg, 4)
116            )?;
117            writeln!(loss_csv, "{},{}", it + 1, fmt_g(avg))?;
118            err_sum = 0.0;
119        }
120    }
121    loss_csv.flush()?;
122
123    // ---- Evaluation (real load units) ----
124    let mut pred = BufWriter::new(File::create(out_dir.join("energy_pred.csv"))?);
125    writeln!(pred, "sample,y1_true,y1_pred,y2_true,y2_pred")?;
126    let mut sum_abs = [0.0; 2];
127    let mut sum_sq_res = [0.0; 2];
128    let mut sum_true = [0.0; 2];
129    let mut sum_sq_true = [0.0; 2];
130    for (i, s) in test.iter().enumerate() {
131        nn.feed_forward(&to_input(s, &feat_stats));
132        let learned = nn.learned_values();
133        let mut y_pred = [0.0; 2];
134        for t in 0..2 {
135            y_pred[t] = from_target(learned[t].to_f64(), t, &target_stats);
136            let r = y_pred[t] - s.load[t];
137            sum_abs[t] += r.abs();
138            sum_sq_res[t] += r * r;
139            sum_true[t] += s.load[t];
140            sum_sq_true[t] += s.load[t] * s.load[t];
141        }
142        writeln!(
143            pred,
144            "{i},{},{},{},{}",
145            fmt_g(s.load[0]),
146            fmt_g(y_pred[0]),
147            fmt_g(s.load[1]),
148            fmt_g(y_pred[1])
149        )?;
150    }
151    pred.flush()?;
152
153    let n = test.len() as f64;
154    let mut mae = [0.0; 2];
155    let mut r2 = [0.0; 2];
156    for t in 0..2 {
157        mae[t] = sum_abs[t] / n;
158        let mean_true = sum_true[t] / n;
159        let ss_tot = sum_sq_true[t] - n * mean_true * mean_true;
160        r2[t] = if ss_tot > 1e-9 {
161            1.0 - sum_sq_res[t] / ss_tot
162        } else {
163            0.0
164        };
165    }
166    writeln!(
167        stdout,
168        "\nHeating load (Y1):  MAE={}  R2={}",
169        fmt_fixed(mae[0], 4),
170        fmt_fixed(r2[0], 4)
171    )?;
172    writeln!(
173        stdout,
174        "Cooling load (Y2):  MAE={}  R2={}",
175        fmt_fixed(mae[1], 4),
176        fmt_fixed(r2[1], 4)
177    )?;
178    stdout.flush()
179}
Source

pub fn train(&mut self, targets: &[V; OUT])

One back-propagation step with the network’s optimizer (C++ ChainBackPropagationPolicy).

Examples found in repository?
examples/common/xor_driver.rs (line 146)
107fn run<V: Format>(
108    out_dir: &Path,
109    learning_rate: Option<f64>,
110    momentum: Option<f64>,
111    stdout: &mut dyn Write,
112) -> io::Result<()>
113where
114    Tanh: Activation<V>,
115    Sigmoid: Activation<V>,
116{
117    // The C++ example seeds rand() twice: srand(WEIGHT_INIT_SEED = 1), construct
118    // the network (which draws the initial weights), then srand(7) for the
119    // training samples. Re-seeding a global generator becomes two independent
120    // generator values in Rust. (The two seeds exist because the C++ network used
121    // to be a global, built before main() seeded rand(), i.e. from glibc's default
122    // seed of 1; tinymind PR #236 made that explicit without changing any output.)
123    let mut init_rng = GlibcRand::new(WEIGHT_INIT_SEED);
124    let mut nn = NeuralNetwork::<V>::new(|| V::random_weight(init_rng.next_i32()));
125    let mut rng = GlibcRand::new(RANDOM_SEED);
126    if let Some(lr) = learning_rate {
127        nn.set_learning_rate(V::from_f64_trunc(lr));
128    }
129    if let Some(m) = momentum {
130        nn.set_momentum_rate(V::from_f64_trunc(m));
131    }
132
133    let mut results = BufWriter::new(File::create(out_dir.join("nn_fixed_xor.txt"))?);
134    let mut curve = BufWriter::new(File::create(out_dir.join("xor_training.csv"))?);
135    writeln!(curve, "iteration,avg_error")?;
136
137    write_header(&mut results)?;
138
139    let mut avg_error = V::ZERO;
140    for i in 0..TRAINING_ITERATIONS {
141        let (inputs, target) = generate_xor_training_value::<V>(&mut rng);
142
143        nn.feed_forward(&inputs);
144        let error = nn.calculate_error(&target);
145        if !error.is_within_zero_tolerance() {
146            nn.train(&target);
147        }
148        let learned = nn.learned_values();
149
150        store_network_properties(&nn, &mut results, &target, &learned)?;
151        writeln!(results, "{error}")?;
152
153        // Accumulate |error| in raw LSBs; the average divides it back down.
154        avg_error += error.abs();
155        if (i + 1) % NUM_SAMPLES_AVG_ERROR == 0 {
156            avg_error = avg_error / V::from_int(NUM_SAMPLES_AVG_ERROR as i32);
157            writeln!(stdout, "Iteration: {} Average Error: {}", i + 1, avg_error)?;
158            writeln!(curve, "{},{}", i + 1, fmt_g(evaluate_xor_error(&mut nn)))?;
159            avg_error = V::ZERO;
160        }
161    }
162
163    // Success = every XOR pattern lands on the correct side of 0.5.
164    let mut correct = 0;
165    for [a, b, expected] in XOR_CASES {
166        let pred = predict(&mut nn, V::from_int(a), V::from_int(b));
167        let ok = (pred >= 0.5) == (expected == 1);
168        correct += u32::from(ok);
169        writeln!(
170            stdout,
171            "  {a} ^ {b} = {expected}  pred={}{}",
172            fmt_g(pred),
173            if ok { "  ok" } else { "  WRONG" }
174        )?;
175    }
176    writeln!(
177        stdout,
178        "{correct}/4 patterns classified correctly. Final 4-case error: {}",
179        fmt_g(evaluate_xor_error(&mut nn))
180    )?;
181
182    // Decision surface over the [0,1]^2 grid.
183    let mut surf = BufWriter::new(File::create(out_dir.join("xor_decision_surface.csv"))?);
184    writeln!(surf, "x0,x1,prob")?;
185    const G: i32 = 41;
186    for a in 0..G {
187        for b in 0..G {
188            let x0 = f64::from(a) / f64::from(G - 1);
189            let x1 = f64::from(b) / f64::from(G - 1);
190            let prob = predict(&mut nn, V::from_f64_trunc(x0), V::from_f64_trunc(x1));
191            writeln!(surf, "{},{},{}", fmt_g(x0), fmt_g(x1), fmt_g(prob))?;
192        }
193    }
194
195    // Flush explicitly so a write error is reported rather than lost in Drop.
196    results.flush()?;
197    curve.flush()?;
198    surf.flush()?;
199    stdout.flush()
200}
More examples
Hide additional examples
examples/common/iris_driver.rs (line 93)
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}
examples/common/energy_driver.rs (line 105)
58pub fn run(out_dir: &Path, data_path: &Path, stdout: &mut dyn Write) -> io::Result<()> {
59    // The C++ seeds rand() with WEIGHT_INIT_SEED, builds the network (drawing
60    // its weights), then re-seeds with 7. Two generators here.
61    let mut init_rng = GlibcRand::new(WEIGHT_INIT_SEED);
62    let mut nn = NeuralNetwork::new(|| random_weight(init_rng.next_i32()));
63
64    let Some(mut data) = load_csv(data_path) else {
65        return Err(io::Error::new(
66            io::ErrorKind::InvalidData,
67            format!("could not open or parse {}", data_path.display()),
68        ));
69    };
70    writeln!(stdout, "Loaded {} rows from ENB2012_data.csv.", data.len())?;
71
72    // Deterministic shuffle + 80/20 split.
73    let mut rng = GlibcRand::new(RANDOM_SEED);
74    for i in (2..=data.len()).rev() {
75        let j = rng.next_i32() as usize % i;
76        data.swap(i - 1, j);
77    }
78    let n_train = data.len() * 4 / 5;
79    let (train, test) = data.split_at(n_train);
80    writeln!(stdout, "Train: {}  Test: {}", train.len(), test.len())?;
81
82    let feat_stats = fit_stats(train, |s| s.feat);
83    let target_stats = fit_stats(train, |s| s.load);
84
85    // A modest learning rate, no momentum or acceleration, and gradients
86    // clipped to [-1, 1] (C++ GradientClipByValue<ValueType>): a linear output's
87    // unbounded gradient otherwise saturates Q16.16.
88    nn.set_learning_rate(to_q(0.02));
89    nn.set_momentum_rate(to_q(0.0));
90    nn.set_acceleration_rate(to_q(0.0));
91    nn.set_gradient_clip(Some((Q16_16::from_int(-1), Q16_16::ONE)));
92
93    // ---- Training ----
94    let mut loss_csv = BufWriter::new(File::create(out_dir.join("energy_loss.csv"))?);
95    writeln!(loss_csv, "iter,avg_err")?;
96    let mut err_sum = 0.0;
97    for it in 0..ITERATIONS {
98        let s = &train[rng.next_i32() as usize % train.len()];
99        let input = to_input(s, &feat_stats);
100        let target = to_target(s, &target_stats);
101
102        nn.feed_forward(&input);
103        let err = nn.calculate_error(&target);
104        if !err.is_within_zero_tolerance() {
105            nn.train(&target);
106        }
107        err_sum += err.to_f64().abs();
108
109        if (it + 1) % REPORT_EVERY == 0 {
110            let avg = err_sum / f64::from(REPORT_EVERY);
111            writeln!(
112                stdout,
113                "iter {:>6}   avg|err| = {}",
114                it + 1,
115                fmt_fixed(avg, 4)
116            )?;
117            writeln!(loss_csv, "{},{}", it + 1, fmt_g(avg))?;
118            err_sum = 0.0;
119        }
120    }
121    loss_csv.flush()?;
122
123    // ---- Evaluation (real load units) ----
124    let mut pred = BufWriter::new(File::create(out_dir.join("energy_pred.csv"))?);
125    writeln!(pred, "sample,y1_true,y1_pred,y2_true,y2_pred")?;
126    let mut sum_abs = [0.0; 2];
127    let mut sum_sq_res = [0.0; 2];
128    let mut sum_true = [0.0; 2];
129    let mut sum_sq_true = [0.0; 2];
130    for (i, s) in test.iter().enumerate() {
131        nn.feed_forward(&to_input(s, &feat_stats));
132        let learned = nn.learned_values();
133        let mut y_pred = [0.0; 2];
134        for t in 0..2 {
135            y_pred[t] = from_target(learned[t].to_f64(), t, &target_stats);
136            let r = y_pred[t] - s.load[t];
137            sum_abs[t] += r.abs();
138            sum_sq_res[t] += r * r;
139            sum_true[t] += s.load[t];
140            sum_sq_true[t] += s.load[t] * s.load[t];
141        }
142        writeln!(
143            pred,
144            "{i},{},{},{},{}",
145            fmt_g(s.load[0]),
146            fmt_g(y_pred[0]),
147            fmt_g(s.load[1]),
148            fmt_g(y_pred[1])
149        )?;
150    }
151    pred.flush()?;
152
153    let n = test.len() as f64;
154    let mut mae = [0.0; 2];
155    let mut r2 = [0.0; 2];
156    for t in 0..2 {
157        mae[t] = sum_abs[t] / n;
158        let mean_true = sum_true[t] / n;
159        let ss_tot = sum_sq_true[t] - n * mean_true * mean_true;
160        r2[t] = if ss_tot > 1e-9 {
161            1.0 - sum_sq_res[t] / ss_tot
162        } else {
163            0.0
164        };
165    }
166    writeln!(
167        stdout,
168        "\nHeating load (Y1):  MAE={}  R2={}",
169        fmt_fixed(mae[0], 4),
170        fmt_fixed(r2[0], 4)
171    )?;
172    writeln!(
173        stdout,
174        "Cooling load (Y2):  MAE={}  R2={}",
175        fmt_fixed(mae[1], 4),
176        fmt_fixed(r2[1], 4)
177    )?;
178    stdout.flush()
179}
Source§

impl<V: Copy, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt> MultilayerPerceptron<V, H, O, IN, HID, OUT, Opt>

Weight getters. These need no activation bounds, so they live in their own impl block. Each returns a whole matrix rather than taking an index, so none of them can panic; the layout matches the order tinymind’s NetworkPropertiesFileManager writes the weights in.

Source

pub fn optimizer(&self) -> &Opt

The optimizer, for example to read Adam::timestep.

Source

pub fn input_weights(&self) -> [[V; HID]; IN]

Input-to-hidden weights: input_weights()[input][hidden].

Examples found in repository?
examples/common/xor_driver.rs (line 263)
257fn store_network_properties<V: Format>(
258    nn: &NeuralNetwork<V>,
259    out: &mut impl Write,
260    expected: &[V; NUMBER_OF_OUTPUTS],
261    learned: &[V; NUMBER_OF_OUTPUTS],
262) -> io::Result<()> {
263    for row in nn.input_weights() {
264        for w in row {
265            write!(out, "{w},")?;
266        }
267    }
268    for w in nn.input_bias_weights() {
269        write!(out, "{w},")?;
270    }
271    for row in nn.hidden_weights() {
272        for w in row {
273            write!(out, "{w},")?;
274        }
275    }
276    for w in nn.hidden_bias_weights() {
277        write!(out, "{w},")?;
278    }
279    for value in expected.iter().chain(learned) {
280        write!(out, "{value},")?;
281    }
282    Ok(())
283}
Source

pub fn input_bias_weights(&self) -> [V; HID]

Input-layer bias to hidden neuron weights: input_bias_weights()[hidden].

Examples found in repository?
examples/common/xor_driver.rs (line 268)
257fn store_network_properties<V: Format>(
258    nn: &NeuralNetwork<V>,
259    out: &mut impl Write,
260    expected: &[V; NUMBER_OF_OUTPUTS],
261    learned: &[V; NUMBER_OF_OUTPUTS],
262) -> io::Result<()> {
263    for row in nn.input_weights() {
264        for w in row {
265            write!(out, "{w},")?;
266        }
267    }
268    for w in nn.input_bias_weights() {
269        write!(out, "{w},")?;
270    }
271    for row in nn.hidden_weights() {
272        for w in row {
273            write!(out, "{w},")?;
274        }
275    }
276    for w in nn.hidden_bias_weights() {
277        write!(out, "{w},")?;
278    }
279    for value in expected.iter().chain(learned) {
280        write!(out, "{value},")?;
281    }
282    Ok(())
283}
Source

pub fn hidden_weights(&self) -> [[V; OUT]; HID]

Hidden-to-output weights: hidden_weights()[hidden][output].

Examples found in repository?
examples/common/xor_driver.rs (line 271)
257fn store_network_properties<V: Format>(
258    nn: &NeuralNetwork<V>,
259    out: &mut impl Write,
260    expected: &[V; NUMBER_OF_OUTPUTS],
261    learned: &[V; NUMBER_OF_OUTPUTS],
262) -> io::Result<()> {
263    for row in nn.input_weights() {
264        for w in row {
265            write!(out, "{w},")?;
266        }
267    }
268    for w in nn.input_bias_weights() {
269        write!(out, "{w},")?;
270    }
271    for row in nn.hidden_weights() {
272        for w in row {
273            write!(out, "{w},")?;
274        }
275    }
276    for w in nn.hidden_bias_weights() {
277        write!(out, "{w},")?;
278    }
279    for value in expected.iter().chain(learned) {
280        write!(out, "{value},")?;
281    }
282    Ok(())
283}
Source

pub fn hidden_bias_weights(&self) -> [V; OUT]

Hidden-layer bias to output neuron weights: hidden_bias_weights()[output].

Examples found in repository?
examples/common/xor_driver.rs (line 276)
257fn store_network_properties<V: Format>(
258    nn: &NeuralNetwork<V>,
259    out: &mut impl Write,
260    expected: &[V; NUMBER_OF_OUTPUTS],
261    learned: &[V; NUMBER_OF_OUTPUTS],
262) -> io::Result<()> {
263    for row in nn.input_weights() {
264        for w in row {
265            write!(out, "{w},")?;
266        }
267    }
268    for w in nn.input_bias_weights() {
269        write!(out, "{w},")?;
270    }
271    for row in nn.hidden_weights() {
272        for w in row {
273            write!(out, "{w},")?;
274        }
275    }
276    for w in nn.hidden_bias_weights() {
277        write!(out, "{w},")?;
278    }
279    for value in expected.iter().chain(learned) {
280        write!(out, "{value},")?;
281    }
282    Ok(())
283}
Source

pub fn set_input_weights(&mut self, weights: &[[V; HID]; IN])

Replace the input-to-hidden weights, laid out as input_weights returns them. Only the weights change; the training state (delta weights, gradients) is kept, as with the C++ setInputLayerWeightForNeuronAndConnection.

Source

pub fn set_input_bias_weights(&mut self, weights: &[V; HID])

Replace the input-layer bias weights (C++ setInputLayerBiasWeightForConnection).

Source

pub fn set_hidden_weights(&mut self, weights: &[[V; OUT]; HID])

Replace the hidden-to-output weights (C++ setHiddenLayerWeightForNeuronAndConnection).

Source

pub fn set_hidden_bias_weights(&mut self, weights: &[V; OUT])

Replace the hidden-layer bias weights (C++ setHiddenLayerBiasNeuronWeightForConnection).

Source

pub fn set_weights(&mut self, from: &InferencePerceptron<V, H, O, IN, HID, OUT>)

Load every weight from an inference network of the same shape, for example to fine-tune shipped weights on the device.

Source

pub fn to_inference(&self) -> InferencePerceptron<V, H, O, IN, HID, OUT>

The trained network as an InferencePerceptron: the same weights and the same outputs, bit for bit, without the training state.

Auto Trait Implementations§

§

impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt> Forget for MultilayerPerceptron<V, H, O, IN, HID, OUT, Opt>

§

impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt> Freeze for MultilayerPerceptron<V, H, O, IN, HID, OUT, Opt>
where [Neuron<V, HID>; IN]: Freeze, Neuron<V, HID>: Freeze, [Neuron<V, OUT>; HID]: Freeze, Neuron<V, OUT>: Freeze, [Neuron<V, 1>; OUT]: Freeze, V: Freeze, Option<(V, V)>: Freeze, Opt: Freeze, PhantomData<fn() -> (H, O)>: Freeze,

§

impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt> RefUnwindSafe for MultilayerPerceptron<V, H, O, IN, HID, OUT, Opt>
where [Neuron<V, HID>; IN]: RefUnwindSafe, Neuron<V, HID>: RefUnwindSafe, [Neuron<V, OUT>; HID]: RefUnwindSafe, Neuron<V, OUT>: RefUnwindSafe, [Neuron<V, 1>; OUT]: RefUnwindSafe, V: RefUnwindSafe, Option<(V, V)>: RefUnwindSafe, Opt: RefUnwindSafe, PhantomData<fn() -> (H, O)>: RefUnwindSafe,

§

impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt> Send for MultilayerPerceptron<V, H, O, IN, HID, OUT, Opt>
where [Neuron<V, HID>; IN]: Send, Neuron<V, HID>: Send, [Neuron<V, OUT>; HID]: Send, Neuron<V, OUT>: Send, [Neuron<V, 1>; OUT]: Send, V: Send, Option<(V, V)>: Send, Opt: Send, PhantomData<fn() -> (H, O)>: Send,

§

impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt> Sync for MultilayerPerceptron<V, H, O, IN, HID, OUT, Opt>
where [Neuron<V, HID>; IN]: Sync, Neuron<V, HID>: Sync, [Neuron<V, OUT>; HID]: Sync, Neuron<V, OUT>: Sync, [Neuron<V, 1>; OUT]: Sync, V: Sync, Option<(V, V)>: Sync, Opt: Sync, PhantomData<fn() -> (H, O)>: Sync,

§

impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt> Unpin for MultilayerPerceptron<V, H, O, IN, HID, OUT, Opt>
where [Neuron<V, HID>; IN]: Unpin, Neuron<V, HID>: Unpin, [Neuron<V, OUT>; HID]: Unpin, Neuron<V, OUT>: Unpin, [Neuron<V, 1>; OUT]: Unpin, V: Unpin, Option<(V, V)>: Unpin, Opt: Unpin, PhantomData<fn() -> (H, O)>: Unpin,

§

impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt> UnsafeUnpin for MultilayerPerceptron<V, H, O, IN, HID, OUT, Opt>
where [Neuron<V, HID>; IN]: UnsafeUnpin, Neuron<V, HID>: UnsafeUnpin, [Neuron<V, OUT>; HID]: UnsafeUnpin, Neuron<V, OUT>: UnsafeUnpin, [Neuron<V, 1>; OUT]: UnsafeUnpin, V: UnsafeUnpin, Option<(V, V)>: UnsafeUnpin, Opt: UnsafeUnpin, PhantomData<fn() -> (H, O)>: UnsafeUnpin,

§

impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt> UnwindSafe for MultilayerPerceptron<V, H, O, IN, HID, OUT, Opt>
where [Neuron<V, HID>; IN]: UnwindSafe, Neuron<V, HID>: UnwindSafe, [Neuron<V, OUT>; HID]: UnwindSafe, Neuron<V, OUT>: UnwindSafe, [Neuron<V, 1>; OUT]: UnwindSafe, V: UnwindSafe, Option<(V, V)>: UnwindSafe, Opt: UnwindSafe, PhantomData<fn() -> (H, O)>: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.