rfann 0.1.0

A pure Rust implementation of the Fast Artificial Neural Network (FANN) library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
//! Adam and AdamW optimizers for neural network training
//!
//! These optimizers provide significant convergence improvements over traditional SGD:
//! - Adam: Adaptive moment estimation with bias correction
//! - AdamW: Adam with decoupled weight decay (better regularization)
//!
//! Expected performance gains:
//! - 2-5x faster convergence in terms of epochs needed
//! - Better handling of sparse gradients and noisy data
//! - Adaptive learning rates per parameter

#![allow(clippy::needless_range_loop)]

use super::*;
use num_traits::Float;
use std::collections::HashMap;

/// Adam optimizer implementation
/// Uses adaptive moment estimation with bias correction for faster convergence
pub struct Adam<T: Float + Send + Default> {
    learning_rate: T,
    beta1: T,
    beta2: T,
    epsilon: T,
    weight_decay: T,
    error_function: Box<dyn ErrorFunction<T>>,

    // Moment estimates
    m_weights: Vec<Vec<T>>, // First moment (momentum)
    v_weights: Vec<Vec<T>>, // Second moment (uncentered variance)
    m_biases: Vec<Vec<T>>,
    v_biases: Vec<Vec<T>>,

    // Step counter for bias correction
    step: usize,

    callback: Option<TrainingCallback<T>>,
}

impl<T: Float + Send + Default> Adam<T> {
    /// Create a new Adam optimizer with default parameters
    pub fn new(learning_rate: T) -> Self {
        Self {
            learning_rate,
            beta1: T::from(0.9).unwrap(),
            beta2: T::from(0.999).unwrap(),
            epsilon: T::from(1e-8).unwrap(),
            weight_decay: T::zero(),
            error_function: Box::new(MseError),
            m_weights: Vec::new(),
            v_weights: Vec::new(),
            m_biases: Vec::new(),
            v_biases: Vec::new(),
            step: 0,
            callback: None,
        }
    }

    /// Set beta1 parameter (momentum coefficient)
    pub fn with_beta1(mut self, beta1: T) -> Self {
        self.beta1 = beta1;
        self
    }

    /// Set beta2 parameter (variance coefficient)
    pub fn with_beta2(mut self, beta2: T) -> Self {
        self.beta2 = beta2;
        self
    }

    /// Set epsilon for numerical stability
    pub fn with_epsilon(mut self, epsilon: T) -> Self {
        self.epsilon = epsilon;
        self
    }

    /// Set weight decay (L2 regularization)
    pub fn with_weight_decay(mut self, weight_decay: T) -> Self {
        self.weight_decay = weight_decay;
        self
    }

    /// Set error function
    pub fn with_error_function(mut self, error_function: Box<dyn ErrorFunction<T>>) -> Self {
        self.error_function = error_function;
        self
    }

    /// Initialize moment estimates for the network
    fn initialize_moments(&mut self, network: &Network<T>) {
        if self.m_weights.is_empty() {
            self.m_weights = network
                .layers
                .iter()
                .skip(1) // Skip input layer
                .map(|layer| {
                    let num_neurons = layer.neurons.len();
                    let num_connections = if layer.neurons.is_empty() {
                        0
                    } else {
                        layer.neurons[0].connections.len()
                    };
                    vec![T::zero(); num_neurons * num_connections]
                })
                .collect();

            self.v_weights = self.m_weights.clone();

            self.m_biases = network
                .layers
                .iter()
                .skip(1) // Skip input layer
                .map(|layer| vec![T::zero(); layer.neurons.len()])
                .collect();

            self.v_biases = self.m_biases.clone();
        }
    }

    /// Update parameters using Adam algorithm
    fn update_parameters(
        &mut self,
        network: &mut Network<T>,
        weight_gradients: &[Vec<T>],
        bias_gradients: &[Vec<T>],
    ) {
        self.step += 1;

        // Bias correction factors
        let lr_t = self.learning_rate * (T::one() - self.beta2.powi(self.step as i32)).sqrt()
            / (T::one() - self.beta1.powi(self.step as i32));

        // Compute weight updates
        let mut weight_updates = Vec::new();
        for layer_idx in 0..weight_gradients.len() {
            let mut layer_updates = Vec::new();
            for i in 0..weight_gradients[layer_idx].len() {
                let grad = weight_gradients[layer_idx][i];

                // Update biased first moment estimate
                self.m_weights[layer_idx][i] =
                    self.beta1 * self.m_weights[layer_idx][i] + (T::one() - self.beta1) * grad;

                // Update biased second moment estimate
                self.v_weights[layer_idx][i] = self.beta2 * self.v_weights[layer_idx][i]
                    + (T::one() - self.beta2) * grad * grad;

                // Compute parameter update
                let update = lr_t * self.m_weights[layer_idx][i]
                    / (self.v_weights[layer_idx][i].sqrt() + self.epsilon);

                layer_updates.push(-update);
            }
            weight_updates.push(layer_updates);
        }

        // Compute bias updates
        let mut bias_updates = Vec::new();
        for layer_idx in 0..bias_gradients.len() {
            let mut layer_updates = Vec::new();
            for i in 0..bias_gradients[layer_idx].len() {
                let grad = bias_gradients[layer_idx][i];

                // Update biased first moment estimate
                self.m_biases[layer_idx][i] =
                    self.beta1 * self.m_biases[layer_idx][i] + (T::one() - self.beta1) * grad;

                // Update biased second moment estimate
                self.v_biases[layer_idx][i] = self.beta2 * self.v_biases[layer_idx][i]
                    + (T::one() - self.beta2) * grad * grad;

                // Compute parameter update
                let update = lr_t * self.m_biases[layer_idx][i]
                    / (self.v_biases[layer_idx][i].sqrt() + self.epsilon);

                layer_updates.push(-update);
            }
            bias_updates.push(layer_updates);
        }

        // Apply weight decay if specified (Adam approach - apply to gradients)
        if self.weight_decay > T::zero() {
            for layer_updates in &mut weight_updates {
                for update in layer_updates {
                    *update = *update - self.learning_rate * self.weight_decay;
                }
            }
        }

        // Apply updates using existing helper
        super::helpers::apply_updates_to_network(network, &weight_updates, &bias_updates);
    }
}

impl<T: Float + Send + Default> TrainingAlgorithm<T> for Adam<T> {
    fn train_epoch(
        &mut self,
        network: &mut Network<T>,
        data: &TrainingData<T>,
    ) -> Result<T, TrainingError> {
        use super::helpers::*;

        self.initialize_moments(network);

        let mut total_error = T::zero();

        // Convert network to simplified form for easier manipulation
        let simple_network = network_to_simple(network);

        // Accumulate gradients over entire batch
        let mut accumulated_weight_gradients = simple_network
            .weights
            .iter()
            .map(|w| vec![T::zero(); w.len()])
            .collect::<Vec<_>>();
        let mut accumulated_bias_gradients = simple_network
            .biases
            .iter()
            .map(|b| vec![T::zero(); b.len()])
            .collect::<Vec<_>>();

        // Process all samples in the batch
        for (input, desired_output) in data.inputs.iter().zip(data.outputs.iter()) {
            // Forward propagation to get all layer activations
            let activations = forward_propagate(&simple_network, input);

            // Get output from last layer
            let output = &activations[activations.len() - 1];

            // Calculate error
            total_error = total_error + self.error_function.calculate(output, desired_output);

            // Calculate gradients using backpropagation
            let (weight_gradients, bias_gradients) = calculate_gradients(
                &simple_network,
                &activations,
                desired_output,
                self.error_function.as_ref(),
            );

            // Accumulate gradients
            for layer_idx in 0..weight_gradients.len() {
                for i in 0..weight_gradients[layer_idx].len() {
                    accumulated_weight_gradients[layer_idx][i] =
                        accumulated_weight_gradients[layer_idx][i] + weight_gradients[layer_idx][i];
                }
                for i in 0..bias_gradients[layer_idx].len() {
                    accumulated_bias_gradients[layer_idx][i] =
                        accumulated_bias_gradients[layer_idx][i] + bias_gradients[layer_idx][i];
                }
            }
        }

        // Average gradients over batch size
        let batch_size = T::from(data.inputs.len()).unwrap();
        for layer_idx in 0..accumulated_weight_gradients.len() {
            for i in 0..accumulated_weight_gradients[layer_idx].len() {
                accumulated_weight_gradients[layer_idx][i] =
                    accumulated_weight_gradients[layer_idx][i] / batch_size;
            }
            for i in 0..accumulated_bias_gradients[layer_idx].len() {
                accumulated_bias_gradients[layer_idx][i] =
                    accumulated_bias_gradients[layer_idx][i] / batch_size;
            }
        }

        // Update parameters using Adam
        self.update_parameters(
            network,
            &accumulated_weight_gradients,
            &accumulated_bias_gradients,
        );

        Ok(total_error / batch_size)
    }

    fn calculate_error(&self, network: &Network<T>, data: &TrainingData<T>) -> T {
        let mut total_error = T::zero();
        let mut network_clone = network.clone();

        for (input, desired_output) in data.inputs.iter().zip(data.outputs.iter()) {
            let output = network_clone.run(input);
            total_error = total_error + self.error_function.calculate(&output, desired_output);
        }

        total_error / T::from(data.inputs.len()).unwrap()
    }

    fn count_bit_fails(
        &self,
        network: &Network<T>,
        data: &TrainingData<T>,
        bit_fail_limit: T,
    ) -> usize {
        let mut bit_fails = 0;
        let mut network_clone = network.clone();

        for (input, desired_output) in data.inputs.iter().zip(data.outputs.iter()) {
            let output = network_clone.run(input);
            for (&actual, &desired) in output.iter().zip(desired_output.iter()) {
                if (actual - desired).abs() > bit_fail_limit {
                    bit_fails += 1;
                }
            }
        }

        bit_fails
    }

    fn save_state(&self) -> TrainingState<T> {
        let mut state = HashMap::new();
        state.insert("learning_rate".to_string(), vec![self.learning_rate]);
        state.insert("beta1".to_string(), vec![self.beta1]);
        state.insert("beta2".to_string(), vec![self.beta2]);
        state.insert("epsilon".to_string(), vec![self.epsilon]);
        state.insert("weight_decay".to_string(), vec![self.weight_decay]);
        state.insert("step".to_string(), vec![T::from(self.step).unwrap()]);

        TrainingState {
            epoch: 0,
            best_error: T::from(f32::MAX).unwrap(),
            algorithm_specific: state,
        }
    }

    fn restore_state(&mut self, state: TrainingState<T>) {
        if let Some(lr) = state.algorithm_specific.get("learning_rate") {
            if !lr.is_empty() {
                self.learning_rate = lr[0];
            }
        }
        if let Some(b1) = state.algorithm_specific.get("beta1") {
            if !b1.is_empty() {
                self.beta1 = b1[0];
            }
        }
        if let Some(b2) = state.algorithm_specific.get("beta2") {
            if !b2.is_empty() {
                self.beta2 = b2[0];
            }
        }
        if let Some(eps) = state.algorithm_specific.get("epsilon") {
            if !eps.is_empty() {
                self.epsilon = eps[0];
            }
        }
        if let Some(wd) = state.algorithm_specific.get("weight_decay") {
            if !wd.is_empty() {
                self.weight_decay = wd[0];
            }
        }
        if let Some(s) = state.algorithm_specific.get("step") {
            if !s.is_empty() {
                self.step = s[0].to_usize().unwrap_or(0);
            }
        }
    }

    fn set_callback(&mut self, callback: TrainingCallback<T>) {
        self.callback = Some(callback);
    }

    fn call_callback(
        &mut self,
        epoch: usize,
        network: &Network<T>,
        data: &TrainingData<T>,
    ) -> bool {
        let error = self.calculate_error(network, data);
        if let Some(ref mut callback) = self.callback {
            callback(epoch, error)
        } else {
            true
        }
    }
}

/// AdamW optimizer implementation
/// Adam with decoupled weight decay for better regularization
pub struct AdamW<T: Float + Send + Default> {
    learning_rate: T,
    beta1: T,
    beta2: T,
    epsilon: T,
    weight_decay: T,
    error_function: Box<dyn ErrorFunction<T>>,

    // Moment estimates
    m_weights: Vec<Vec<T>>,
    v_weights: Vec<Vec<T>>,
    m_biases: Vec<Vec<T>>,
    v_biases: Vec<Vec<T>>,

    // Step counter for bias correction
    step: usize,

    callback: Option<TrainingCallback<T>>,
}

impl<T: Float + Send + Default> AdamW<T> {
    /// Create a new AdamW optimizer with default parameters
    pub fn new(learning_rate: T) -> Self {
        Self {
            learning_rate,
            beta1: T::from(0.9).unwrap(),
            beta2: T::from(0.999).unwrap(),
            epsilon: T::from(1e-8).unwrap(),
            weight_decay: T::from(0.01).unwrap(), // Common default for AdamW
            error_function: Box::new(MseError),
            m_weights: Vec::new(),
            v_weights: Vec::new(),
            m_biases: Vec::new(),
            v_biases: Vec::new(),
            step: 0,
            callback: None,
        }
    }

    /// Set beta1 parameter (momentum coefficient)
    pub fn with_beta1(mut self, beta1: T) -> Self {
        self.beta1 = beta1;
        self
    }

    /// Set beta2 parameter (variance coefficient)
    pub fn with_beta2(mut self, beta2: T) -> Self {
        self.beta2 = beta2;
        self
    }

    /// Set epsilon for numerical stability
    pub fn with_epsilon(mut self, epsilon: T) -> Self {
        self.epsilon = epsilon;
        self
    }

    /// Set weight decay (decoupled from gradient-based updates)
    pub fn with_weight_decay(mut self, weight_decay: T) -> Self {
        self.weight_decay = weight_decay;
        self
    }

    /// Set error function
    pub fn with_error_function(mut self, error_function: Box<dyn ErrorFunction<T>>) -> Self {
        self.error_function = error_function;
        self
    }

    /// Initialize moment estimates for the network
    fn initialize_moments(&mut self, network: &Network<T>) {
        if self.m_weights.is_empty() {
            self.m_weights = network
                .layers
                .iter()
                .skip(1) // Skip input layer
                .map(|layer| {
                    let num_neurons = layer.neurons.len();
                    let num_connections = if layer.neurons.is_empty() {
                        0
                    } else {
                        layer.neurons[0].connections.len()
                    };
                    vec![T::zero(); num_neurons * num_connections]
                })
                .collect();

            self.v_weights = self.m_weights.clone();

            self.m_biases = network
                .layers
                .iter()
                .skip(1) // Skip input layer
                .map(|layer| vec![T::zero(); layer.neurons.len()])
                .collect();

            self.v_biases = self.m_biases.clone();
        }
    }

    /// Apply AdamW updates to the network (with decoupled weight decay)
    fn apply_adamw_updates(
        &mut self,
        network: &mut Network<T>,
        weight_gradients: &[Vec<T>],
        bias_gradients: &[Vec<T>],
        lr_t: T,
    ) {
        // Compute and apply weight updates with decoupled weight decay
        let mut weight_updates = Vec::new();
        for layer_idx in 0..weight_gradients.len() {
            let mut layer_updates = Vec::new();
            for i in 0..weight_gradients[layer_idx].len() {
                let adaptive_update = lr_t * self.m_weights[layer_idx][i]
                    / (self.v_weights[layer_idx][i].sqrt() + self.epsilon);

                // In AdamW, weight decay is applied directly to weights, not gradients
                layer_updates.push(-adaptive_update);
            }
            weight_updates.push(layer_updates);
        }

        // Compute and apply bias updates (no weight decay for biases)
        let mut bias_updates = Vec::new();
        for layer_idx in 0..bias_gradients.len() {
            let mut layer_updates = Vec::new();
            for i in 0..bias_gradients[layer_idx].len() {
                let update = lr_t * self.m_biases[layer_idx][i]
                    / (self.v_biases[layer_idx][i].sqrt() + self.epsilon);
                layer_updates.push(-update);
            }
            bias_updates.push(layer_updates);
        }

        // Apply updates using existing helper
        super::helpers::apply_updates_to_network(network, &weight_updates, &bias_updates);

        // Apply decoupled weight decay directly to weights
        if self.weight_decay > T::zero() {
            self.apply_decoupled_weight_decay(network);
        }
    }

    /// Apply decoupled weight decay directly to weights (AdamW approach)
    fn apply_decoupled_weight_decay(&self, network: &mut Network<T>) {
        let decay_factor = T::one() - self.learning_rate * self.weight_decay;

        for layer_idx in 1..network.layers.len() {
            let current_layer = &mut network.layers[layer_idx];

            for neuron in &mut current_layer.neurons {
                if !neuron.is_bias {
                    // Apply weight decay to all connections except bias (index 0)
                    for connection in neuron.connections.iter_mut().skip(1) {
                        connection.weight = connection.weight * decay_factor;
                    }
                }
            }
        }
    }
}

impl<T: Float + Send + Default> TrainingAlgorithm<T> for AdamW<T> {
    fn train_epoch(
        &mut self,
        network: &mut Network<T>,
        data: &TrainingData<T>,
    ) -> Result<T, TrainingError> {
        use super::helpers::*;

        self.initialize_moments(network);
        self.step += 1;

        let mut total_error = T::zero();

        // Convert network to simplified form for easier manipulation
        let simple_network = network_to_simple(network);

        // Accumulate gradients over entire batch
        let mut accumulated_weight_gradients = simple_network
            .weights
            .iter()
            .map(|w| vec![T::zero(); w.len()])
            .collect::<Vec<_>>();
        let mut accumulated_bias_gradients = simple_network
            .biases
            .iter()
            .map(|b| vec![T::zero(); b.len()])
            .collect::<Vec<_>>();

        // Process all samples in the batch
        for (input, desired_output) in data.inputs.iter().zip(data.outputs.iter()) {
            // Forward propagation to get all layer activations
            let activations = forward_propagate(&simple_network, input);

            // Get output from last layer
            let output = &activations[activations.len() - 1];

            // Calculate error
            total_error = total_error + self.error_function.calculate(output, desired_output);

            // Calculate gradients using backpropagation
            let (weight_gradients, bias_gradients) = calculate_gradients(
                &simple_network,
                &activations,
                desired_output,
                self.error_function.as_ref(),
            );

            // Accumulate gradients
            for layer_idx in 0..weight_gradients.len() {
                for i in 0..weight_gradients[layer_idx].len() {
                    accumulated_weight_gradients[layer_idx][i] =
                        accumulated_weight_gradients[layer_idx][i] + weight_gradients[layer_idx][i];
                }
                for i in 0..bias_gradients[layer_idx].len() {
                    accumulated_bias_gradients[layer_idx][i] =
                        accumulated_bias_gradients[layer_idx][i] + bias_gradients[layer_idx][i];
                }
            }
        }

        // Average gradients over batch size
        let batch_size = T::from(data.inputs.len()).unwrap();
        for layer_idx in 0..accumulated_weight_gradients.len() {
            for i in 0..accumulated_weight_gradients[layer_idx].len() {
                accumulated_weight_gradients[layer_idx][i] =
                    accumulated_weight_gradients[layer_idx][i] / batch_size;
            }
            for i in 0..accumulated_bias_gradients[layer_idx].len() {
                accumulated_bias_gradients[layer_idx][i] =
                    accumulated_bias_gradients[layer_idx][i] / batch_size;
            }
        }

        // Update moment estimates
        for layer_idx in 0..accumulated_weight_gradients.len() {
            for i in 0..accumulated_weight_gradients[layer_idx].len() {
                let grad = accumulated_weight_gradients[layer_idx][i];

                // Update biased first moment estimate
                self.m_weights[layer_idx][i] =
                    self.beta1 * self.m_weights[layer_idx][i] + (T::one() - self.beta1) * grad;

                // Update biased second moment estimate
                self.v_weights[layer_idx][i] = self.beta2 * self.v_weights[layer_idx][i]
                    + (T::one() - self.beta2) * grad * grad;
            }
        }

        // Update bias moments
        for layer_idx in 0..accumulated_bias_gradients.len() {
            for i in 0..accumulated_bias_gradients[layer_idx].len() {
                let grad = accumulated_bias_gradients[layer_idx][i];

                // Update biased first moment estimate
                self.m_biases[layer_idx][i] =
                    self.beta1 * self.m_biases[layer_idx][i] + (T::one() - self.beta1) * grad;

                // Update biased second moment estimate
                self.v_biases[layer_idx][i] = self.beta2 * self.v_biases[layer_idx][i]
                    + (T::one() - self.beta2) * grad * grad;
            }
        }

        // Bias correction factors
        let lr_t = self.learning_rate * (T::one() - self.beta2.powi(self.step as i32)).sqrt()
            / (T::one() - self.beta1.powi(self.step as i32));

        // Apply AdamW updates with decoupled weight decay
        self.apply_adamw_updates(
            network,
            &accumulated_weight_gradients,
            &accumulated_bias_gradients,
            lr_t,
        );

        Ok(total_error / batch_size)
    }

    fn calculate_error(&self, network: &Network<T>, data: &TrainingData<T>) -> T {
        let mut total_error = T::zero();
        let mut network_clone = network.clone();

        for (input, desired_output) in data.inputs.iter().zip(data.outputs.iter()) {
            let output = network_clone.run(input);
            total_error = total_error + self.error_function.calculate(&output, desired_output);
        }

        total_error / T::from(data.inputs.len()).unwrap()
    }

    fn count_bit_fails(
        &self,
        network: &Network<T>,
        data: &TrainingData<T>,
        bit_fail_limit: T,
    ) -> usize {
        let mut bit_fails = 0;
        let mut network_clone = network.clone();

        for (input, desired_output) in data.inputs.iter().zip(data.outputs.iter()) {
            let output = network_clone.run(input);
            for (&actual, &desired) in output.iter().zip(desired_output.iter()) {
                if (actual - desired).abs() > bit_fail_limit {
                    bit_fails += 1;
                }
            }
        }

        bit_fails
    }

    fn save_state(&self) -> TrainingState<T> {
        let mut state = HashMap::new();
        state.insert("learning_rate".to_string(), vec![self.learning_rate]);
        state.insert("beta1".to_string(), vec![self.beta1]);
        state.insert("beta2".to_string(), vec![self.beta2]);
        state.insert("epsilon".to_string(), vec![self.epsilon]);
        state.insert("weight_decay".to_string(), vec![self.weight_decay]);
        state.insert("step".to_string(), vec![T::from(self.step).unwrap()]);

        TrainingState {
            epoch: 0,
            best_error: T::from(f32::MAX).unwrap(),
            algorithm_specific: state,
        }
    }

    fn restore_state(&mut self, state: TrainingState<T>) {
        if let Some(lr) = state.algorithm_specific.get("learning_rate") {
            if !lr.is_empty() {
                self.learning_rate = lr[0];
            }
        }
        if let Some(b1) = state.algorithm_specific.get("beta1") {
            if !b1.is_empty() {
                self.beta1 = b1[0];
            }
        }
        if let Some(b2) = state.algorithm_specific.get("beta2") {
            if !b2.is_empty() {
                self.beta2 = b2[0];
            }
        }
        if let Some(eps) = state.algorithm_specific.get("epsilon") {
            if !eps.is_empty() {
                self.epsilon = eps[0];
            }
        }
        if let Some(wd) = state.algorithm_specific.get("weight_decay") {
            if !wd.is_empty() {
                self.weight_decay = wd[0];
            }
        }
        if let Some(s) = state.algorithm_specific.get("step") {
            if !s.is_empty() {
                self.step = s[0].to_usize().unwrap_or(0);
            }
        }
    }

    fn set_callback(&mut self, callback: TrainingCallback<T>) {
        self.callback = Some(callback);
    }

    fn call_callback(
        &mut self,
        epoch: usize,
        network: &Network<T>,
        data: &TrainingData<T>,
    ) -> bool {
        let error = self.calculate_error(network, data);
        if let Some(ref mut callback) = self.callback {
            callback(epoch, error)
        } else {
            true
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_adam_creation() {
        let adam = Adam::new(0.001f32);
        assert_eq!(adam.learning_rate, 0.001);
        assert_eq!(adam.beta1, 0.9);
        assert_eq!(adam.beta2, 0.999);
        assert_eq!(adam.step, 0);
    }

    #[test]
    fn test_adamw_creation() {
        let adamw = AdamW::new(0.001f32);
        assert_eq!(adamw.learning_rate, 0.001);
        assert_eq!(adamw.beta1, 0.9);
        assert_eq!(adamw.beta2, 0.999);
        assert_eq!(adamw.weight_decay, 0.01);
        assert_eq!(adamw.step, 0);
    }

    #[test]
    fn test_adam_with_parameters() {
        let adam = Adam::new(0.001f32)
            .with_beta1(0.95)
            .with_beta2(0.998)
            .with_epsilon(1e-7)
            .with_weight_decay(0.001);

        assert_eq!(adam.beta1, 0.95);
        assert_eq!(adam.beta2, 0.998);
        assert_eq!(adam.epsilon, 1e-7);
        assert_eq!(adam.weight_decay, 0.001);
    }
}