sklears-neural 0.1.1

Neural network implementations for the sklears machine learning 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
//! Weight initialization strategies for neural networks.
//!
//! This module provides various weight initialization methods that are crucial
//! for proper neural network training. Different initialization strategies are
//! optimal for different activation functions and architectures.

use crate::NeuralResult;
use scirs2_core::ndarray::{Array1, Array2};
use scirs2_core::numeric::FromPrimitive;
use scirs2_core::random::essentials::{Normal, Uniform};
use scirs2_core::random::{Distribution, Rng};
use sklears_core::{error::SklearsError, types::FloatBounds};

/// Weight initialization strategies
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum InitStrategy {
    /// Zero initialization (not recommended for hidden layers)
    Zeros,
    /// Uniform initialization with given range
    Uniform {
        /// Lower bound of uniform range
        low: f64,
        /// Upper bound of uniform range
        high: f64,
    },
    /// Normal/Gaussian initialization
    Normal {
        /// Mean of normal distribution
        mean: f64,
        /// Standard deviation of normal distribution
        std: f64,
    },
    /// Xavier/Glorot uniform initialization
    #[default]
    XavierUniform,
    /// Xavier/Glorot normal initialization  
    XavierNormal,
    /// He uniform initialization (good for ReLU)
    HeUniform,
    /// He normal initialization (good for ReLU)
    HeNormal,
    /// LeCun uniform initialization
    LeCunUniform,
    /// LeCun normal initialization
    LeCunNormal,
    /// Orthogonal initialization
    Orthogonal {
        /// Multiplicative gain factor
        gain: f64,
    },
    /// Truncated normal initialization
    TruncatedNormal {
        /// Mean of the normal distribution
        mean: f64,
        /// Standard deviation of the normal distribution
        std: f64,
        /// Lower truncation bound
        low: f64,
        /// Upper truncation bound
        high: f64,
    },
    /// Variance scaling initialization (general form)
    VarianceScaling {
        /// Scale factor for variance
        scale: f64,
        /// Scaling mode (fan-in, fan-out, or average)
        mode: ScalingMode,
        /// Distribution to use for sampling
        distribution: ScalingDistribution,
    },
}

/// Mode for variance scaling
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScalingMode {
    /// Scale by fan-in (number of input units)
    FanIn,
    /// Scale by fan-out (number of output units)
    FanOut,
    /// Scale by average of fan-in and fan-out
    FanAvg,
}

/// Distribution for variance scaling
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScalingDistribution {
    /// Uniform distribution
    Uniform,
    /// Normal distribution
    Normal,
    /// Truncated normal distribution
    TruncatedNormal,
}

/// Weight initializer
pub struct WeightInitializer<T: FloatBounds> {
    strategy: InitStrategy,
    _phantom: std::marker::PhantomData<T>,
}

impl<T: FloatBounds> WeightInitializer<T> {
    /// Create a new weight initializer with the given strategy
    pub fn new(strategy: InitStrategy) -> Self {
        Self {
            strategy,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Initialize a 2D weight matrix
    pub fn initialize_2d<R: Rng>(
        &self,
        rng: &mut R,
        shape: (usize, usize),
    ) -> NeuralResult<Array2<T>> {
        let (rows, cols) = shape;
        let fan_in = rows;
        let fan_out = cols;

        match self.strategy {
            InitStrategy::Zeros => Ok(Array2::zeros(shape)),

            InitStrategy::Uniform { low, high } => {
                let uniform = Uniform::new(low, high).map_err(|e| {
                    SklearsError::InvalidInput(format!("Invalid uniform distribution: {}", e))
                })?;
                let values: Vec<T> = (0..rows * cols)
                    .map(|_| FromPrimitive::from_f64(uniform.sample(rng)).unwrap_or(T::zero()))
                    .collect();
                Array2::from_shape_vec(shape, values)
                    .map_err(|e| SklearsError::InvalidInput(format!("Shape error: {}", e)))
            }

            InitStrategy::Normal { mean, std } => {
                let normal = Normal::new(mean, std).map_err(|e| {
                    SklearsError::InvalidInput(format!("Invalid normal distribution: {}", e))
                })?;
                let values: Vec<T> = (0..rows * cols)
                    .map(|_| FromPrimitive::from_f64(normal.sample(rng)).unwrap_or(T::zero()))
                    .collect();
                Array2::from_shape_vec(shape, values)
                    .map_err(|e| SklearsError::InvalidInput(format!("Shape error: {}", e)))
            }

            InitStrategy::XavierUniform => {
                let limit = (6.0 / (fan_in + fan_out) as f64).sqrt();
                let uniform = Uniform::new(-limit, limit).map_err(|e| {
                    SklearsError::InvalidInput(format!("Invalid Xavier uniform: {}", e))
                })?;
                let values: Vec<T> = (0..rows * cols)
                    .map(|_| FromPrimitive::from_f64(uniform.sample(rng)).unwrap_or(T::zero()))
                    .collect();
                Array2::from_shape_vec(shape, values)
                    .map_err(|e| SklearsError::InvalidInput(format!("Shape error: {}", e)))
            }

            InitStrategy::XavierNormal => {
                let std = (2.0 / (fan_in + fan_out) as f64).sqrt();
                let normal = Normal::new(0.0, std).map_err(|e| {
                    SklearsError::InvalidInput(format!("Invalid Xavier normal: {}", e))
                })?;
                let values: Vec<T> = (0..rows * cols)
                    .map(|_| FromPrimitive::from_f64(normal.sample(rng)).unwrap_or(T::zero()))
                    .collect();
                Array2::from_shape_vec(shape, values)
                    .map_err(|e| SklearsError::InvalidInput(format!("Shape error: {}", e)))
            }

            InitStrategy::HeUniform => {
                let limit = (6.0 / fan_in as f64).sqrt();
                let uniform = Uniform::new(-limit, limit).map_err(|e| {
                    SklearsError::InvalidInput(format!("Invalid He uniform: {}", e))
                })?;
                let values: Vec<T> = (0..rows * cols)
                    .map(|_| FromPrimitive::from_f64(uniform.sample(rng)).unwrap_or(T::zero()))
                    .collect();
                Array2::from_shape_vec(shape, values)
                    .map_err(|e| SklearsError::InvalidInput(format!("Shape error: {}", e)))
            }

            InitStrategy::HeNormal => {
                let std = (2.0 / fan_in as f64).sqrt();
                let normal = Normal::new(0.0, std)
                    .map_err(|e| SklearsError::InvalidInput(format!("Invalid He normal: {}", e)))?;
                let values: Vec<T> = (0..rows * cols)
                    .map(|_| FromPrimitive::from_f64(normal.sample(rng)).unwrap_or(T::zero()))
                    .collect();
                Array2::from_shape_vec(shape, values)
                    .map_err(|e| SklearsError::InvalidInput(format!("Shape error: {}", e)))
            }

            InitStrategy::LeCunUniform => {
                let limit = (3.0 / fan_in as f64).sqrt();
                let uniform = Uniform::new(-limit, limit).map_err(|e| {
                    SklearsError::InvalidInput(format!("Invalid LeCun uniform: {}", e))
                })?;
                let values: Vec<T> = (0..rows * cols)
                    .map(|_| FromPrimitive::from_f64(uniform.sample(rng)).unwrap_or(T::zero()))
                    .collect();
                Array2::from_shape_vec(shape, values)
                    .map_err(|e| SklearsError::InvalidInput(format!("Shape error: {}", e)))
            }

            InitStrategy::LeCunNormal => {
                let std = (1.0 / fan_in as f64).sqrt();
                let normal = Normal::new(0.0, std).map_err(|e| {
                    SklearsError::InvalidInput(format!("Invalid LeCun normal: {}", e))
                })?;
                let values: Vec<T> = (0..rows * cols)
                    .map(|_| FromPrimitive::from_f64(normal.sample(rng)).unwrap_or(T::zero()))
                    .collect();
                Array2::from_shape_vec(shape, values)
                    .map_err(|e| SklearsError::InvalidInput(format!("Shape error: {}", e)))
            }

            InitStrategy::Orthogonal { gain } => self.orthogonal_init(rng, shape, gain),

            InitStrategy::TruncatedNormal {
                mean,
                std,
                low,
                high,
            } => self.truncated_normal_init(rng, shape, mean, std, low, high),

            InitStrategy::VarianceScaling {
                scale,
                mode,
                distribution,
            } => self.variance_scaling_init(rng, shape, scale, mode, distribution, fan_in, fan_out),
        }
    }

    /// Initialize a 1D bias vector
    pub fn initialize_1d<R: Rng>(&self, rng: &mut R, size: usize) -> NeuralResult<Array1<T>> {
        // For biases, typically use zeros or small values
        match self.strategy {
            InitStrategy::Zeros => Ok(Array1::zeros(size)),
            InitStrategy::Uniform { low, high } => {
                let uniform = Uniform::new(low, high).map_err(|e| {
                    SklearsError::InvalidInput(format!("Invalid uniform distribution: {}", e))
                })?;
                let values: Vec<T> = (0..size)
                    .map(|_| FromPrimitive::from_f64(uniform.sample(rng)).unwrap_or(T::zero()))
                    .collect();
                Ok(Array1::from_vec(values))
            }
            InitStrategy::Normal { mean, std } => {
                let normal = Normal::new(mean, std).map_err(|e| {
                    SklearsError::InvalidInput(format!("Invalid normal distribution: {}", e))
                })?;
                let values: Vec<T> = (0..size)
                    .map(|_| FromPrimitive::from_f64(normal.sample(rng)).unwrap_or(T::zero()))
                    .collect();
                Ok(Array1::from_vec(values))
            }
            // For most other strategies, use zeros for biases
            _ => Ok(Array1::zeros(size)),
        }
    }

    /// Orthogonal initialization using QR decomposition
    fn orthogonal_init<R: Rng>(
        &self,
        rng: &mut R,
        shape: (usize, usize),
        gain: f64,
    ) -> NeuralResult<Array2<T>> {
        let (rows, cols) = shape;

        // Generate random matrix
        let normal = Normal::new(0.0, 1.0).map_err(|e| {
            SklearsError::InvalidInput(format!("Invalid normal for orthogonal: {}", e))
        })?;
        let values: Vec<f64> = (0..rows * cols).map(|_| normal.sample(rng)).collect();
        let mut matrix = Array2::from_shape_vec(shape, values)
            .map_err(|e| SklearsError::InvalidInput(format!("Shape error: {}", e)))?;

        // Perform QR decomposition (simplified version)
        // This is a basic implementation - in practice, you'd use a more robust QR decomposition
        self.gram_schmidt_qr(&mut matrix)?;

        // Apply gain
        matrix.mapv_inplace(|x| x * gain);

        // Convert to target type
        Ok(matrix.mapv(|x| FromPrimitive::from_f64(x).unwrap_or(T::zero())))
    }

    /// Simplified Gram-Schmidt QR decomposition
    fn gram_schmidt_qr(&self, matrix: &mut Array2<f64>) -> NeuralResult<()> {
        let (rows, cols) = matrix.dim();
        let min_dim = rows.min(cols);

        for i in 0..min_dim {
            // Normalize column i
            let mut col_i = matrix.column_mut(i);
            let norm = col_i.mapv(|x| x * x).sum().sqrt();
            if norm > 1e-10 {
                col_i.mapv_inplace(|x| x / norm);
            }

            // Orthogonalize subsequent columns
            for j in (i + 1)..cols {
                let dot_product = matrix.column(i).dot(&matrix.column(j));

                // Get column i values before taking mutable reference to column j
                let col_i_values: Vec<f64> = matrix.column(i).to_vec();
                let mut col_j = matrix.column_mut(j);

                for (c_j, &c_i) in col_j.iter_mut().zip(col_i_values.iter()) {
                    *c_j -= dot_product * c_i;
                }
            }
        }

        Ok(())
    }

    /// Truncated normal initialization
    fn truncated_normal_init<R: Rng>(
        &self,
        rng: &mut R,
        shape: (usize, usize),
        mean: f64,
        std: f64,
        low: f64,
        high: f64,
    ) -> NeuralResult<Array2<T>> {
        let (rows, cols) = shape;
        let normal = Normal::new(mean, std)
            .map_err(|e| SklearsError::InvalidInput(format!("Invalid truncated normal: {}", e)))?;

        let mut values = Vec::with_capacity(rows * cols);

        // Generate values within bounds
        for _ in 0..rows * cols {
            let mut val = normal.sample(rng);
            let mut attempts = 0;

            // Rejection sampling to stay within bounds
            while (val < low || val > high) && attempts < 100 {
                val = normal.sample(rng);
                attempts += 1;
            }

            // If we can't generate a valid value, clamp it
            if val < low {
                val = low;
            } else if val > high {
                val = high;
            }

            values.push(FromPrimitive::from_f64(val).unwrap_or(T::zero()));
        }

        Array2::from_shape_vec(shape, values)
            .map_err(|e| SklearsError::InvalidInput(format!("Shape error: {}", e)))
    }

    /// Variance scaling initialization
    fn variance_scaling_init<R: Rng>(
        &self,
        rng: &mut R,
        shape: (usize, usize),
        scale: f64,
        mode: ScalingMode,
        distribution: ScalingDistribution,
        fan_in: usize,
        fan_out: usize,
    ) -> NeuralResult<Array2<T>> {
        let (rows, cols) = shape;

        let fan = match mode {
            ScalingMode::FanIn => fan_in as f64,
            ScalingMode::FanOut => fan_out as f64,
            ScalingMode::FanAvg => (fan_in + fan_out) as f64 / 2.0,
        };

        let variance = scale / fan;

        match distribution {
            ScalingDistribution::Uniform => {
                let limit = (3.0 * variance).sqrt();
                let uniform = Uniform::new(-limit, limit).map_err(|e| {
                    SklearsError::InvalidInput(format!("Invalid variance scaling uniform: {}", e))
                })?;
                let values: Vec<T> = (0..rows * cols)
                    .map(|_| FromPrimitive::from_f64(uniform.sample(rng)).unwrap_or(T::zero()))
                    .collect();
                Array2::from_shape_vec(shape, values)
                    .map_err(|e| SklearsError::InvalidInput(format!("Shape error: {}", e)))
            }

            ScalingDistribution::Normal => {
                let std = variance.sqrt();
                let normal = Normal::new(0.0, std).map_err(|e| {
                    SklearsError::InvalidInput(format!("Invalid variance scaling normal: {}", e))
                })?;
                let values: Vec<T> = (0..rows * cols)
                    .map(|_| FromPrimitive::from_f64(normal.sample(rng)).unwrap_or(T::zero()))
                    .collect();
                Array2::from_shape_vec(shape, values)
                    .map_err(|e| SklearsError::InvalidInput(format!("Shape error: {}", e)))
            }

            ScalingDistribution::TruncatedNormal => {
                let std = variance.sqrt();
                self.truncated_normal_init(rng, shape, 0.0, std, -2.0 * std, 2.0 * std)
            }
        }
    }
}

/// Convenience functions for common initialization strategies
impl<T: FloatBounds> WeightInitializer<T> {
    /// Xavier/Glorot uniform initialization
    pub fn xavier_uniform() -> Self {
        Self::new(InitStrategy::XavierUniform)
    }

    /// Xavier/Glorot normal initialization
    pub fn xavier_normal() -> Self {
        Self::new(InitStrategy::XavierNormal)
    }

    /// He uniform initialization (good for ReLU)
    pub fn he_uniform() -> Self {
        Self::new(InitStrategy::HeUniform)
    }

    /// He normal initialization (good for ReLU)
    pub fn he_normal() -> Self {
        Self::new(InitStrategy::HeNormal)
    }

    /// LeCun uniform initialization
    pub fn lecun_uniform() -> Self {
        Self::new(InitStrategy::LeCunUniform)
    }

    /// LeCun normal initialization
    pub fn lecun_normal() -> Self {
        Self::new(InitStrategy::LeCunNormal)
    }

    /// Orthogonal initialization with default gain of 1.0
    pub fn orthogonal() -> Self {
        Self::new(InitStrategy::Orthogonal { gain: 1.0 })
    }

    /// Orthogonal initialization with custom gain
    pub fn orthogonal_with_gain(gain: f64) -> Self {
        Self::new(InitStrategy::Orthogonal { gain })
    }

    /// Zero initialization
    pub fn zeros() -> Self {
        Self::new(InitStrategy::Zeros)
    }

    /// Uniform initialization
    pub fn uniform(low: f64, high: f64) -> Self {
        Self::new(InitStrategy::Uniform { low, high })
    }

    /// Normal initialization
    pub fn normal(mean: f64, std: f64) -> Self {
        Self::new(InitStrategy::Normal { mean, std })
    }
}

#[allow(non_snake_case)]
#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_abs_diff_eq;
    use scirs2_core::random::rngs::StdRng;
    use scirs2_core::random::SeedableRng;

    #[test]
    fn test_xavier_uniform_initialization() {
        let mut rng = StdRng::seed_from_u64(42);
        let initializer = WeightInitializer::<f64>::xavier_uniform();

        let weights = initializer
            .initialize_2d(&mut rng, (100, 50))
            .expect("operation should succeed");

        // Check shape
        assert_eq!(weights.dim(), (100, 50));

        // Check that values are in expected range
        let fan_in = 100;
        let fan_out = 50;
        let limit = (6.0 / (fan_in + fan_out) as f64).sqrt();

        for &val in weights.iter() {
            assert!(val >= -limit && val <= limit);
        }

        // Check approximate mean and variance
        let mean = weights.mean().expect("operation should succeed");
        let variance = weights
            .mapv(|x| (x - mean) * (x - mean))
            .mean()
            .expect("operation should succeed");

        assert_abs_diff_eq!(mean, 0.0, epsilon = 0.1);
        assert!(variance > 0.001); // Should have some variance
    }

    #[test]
    fn test_he_normal_initialization() {
        let mut rng = StdRng::seed_from_u64(42);
        let initializer = WeightInitializer::<f64>::he_normal();

        let weights = initializer
            .initialize_2d(&mut rng, (128, 64))
            .expect("operation should succeed");

        // Check shape
        assert_eq!(weights.dim(), (128, 64));

        // For He initialization, variance should be approximately 2/fan_in
        let fan_in = 128;
        let expected_variance = 2.0 / fan_in as f64;

        let mean = weights.mean().expect("operation should succeed");
        let actual_variance = weights
            .mapv(|x| (x - mean) * (x - mean))
            .mean()
            .expect("operation should succeed");

        assert_abs_diff_eq!(mean, 0.0, epsilon = 0.1);
        assert_abs_diff_eq!(actual_variance, expected_variance, epsilon = 0.01);
    }

    #[test]
    fn test_orthogonal_initialization() {
        let mut rng = StdRng::seed_from_u64(42);
        let initializer = WeightInitializer::<f64>::orthogonal();

        let weights = initializer
            .initialize_2d(&mut rng, (10, 10))
            .expect("operation should succeed");

        // Check shape
        assert_eq!(weights.dim(), (10, 10));

        // For square orthogonal matrix, columns should be approximately orthonormal
        // W^T * W should be approximately identity
        let weights_t = weights.t();
        let product = weights_t.dot(&weights);

        // Check diagonal elements are close to 1
        for i in 0..10 {
            assert_abs_diff_eq!(product[[i, i]], 1.0, epsilon = 0.1);
        }

        // Check off-diagonal elements are close to 0
        for i in 0..10 {
            for j in 0..10 {
                if i != j {
                    assert_abs_diff_eq!(product[[i, j]], 0.0, epsilon = 0.1);
                }
            }
        }
    }

    #[test]
    fn test_truncated_normal_initialization() {
        let mut rng = StdRng::seed_from_u64(42);
        let initializer = WeightInitializer::<f64>::new(InitStrategy::TruncatedNormal {
            mean: 0.0,
            std: 1.0,
            low: -2.0,
            high: 2.0,
        });

        let weights = initializer
            .initialize_2d(&mut rng, (100, 100))
            .expect("operation should succeed");

        // Check that all values are within bounds
        for &val in weights.iter() {
            assert!((-2.0..=2.0).contains(&val));
        }

        // Check approximate mean
        let mean = weights.mean().expect("operation should succeed");
        assert_abs_diff_eq!(mean, 0.0, epsilon = 0.2);
    }

    #[test]
    fn test_zeros_initialization() {
        let mut rng = StdRng::seed_from_u64(42);
        let initializer = WeightInitializer::<f64>::zeros();

        let weights = initializer
            .initialize_2d(&mut rng, (50, 30))
            .expect("operation should succeed");
        let biases = initializer
            .initialize_1d(&mut rng, 30)
            .expect("operation should succeed");

        // Check that all values are zero
        for &val in weights.iter() {
            assert_eq!(val, 0.0);
        }

        for &val in biases.iter() {
            assert_eq!(val, 0.0);
        }
    }

    #[test]
    fn test_uniform_initialization() {
        let mut rng = StdRng::seed_from_u64(42);
        let initializer = WeightInitializer::<f64>::uniform(-0.5, 0.5);

        let weights = initializer
            .initialize_2d(&mut rng, (100, 50))
            .expect("operation should succeed");

        // Check that all values are within bounds
        for &val in weights.iter() {
            assert!((-0.5..=0.5).contains(&val));
        }

        // Check approximate mean (should be close to 0 for symmetric range)
        let mean = weights.mean().expect("operation should succeed");
        assert_abs_diff_eq!(mean, 0.0, epsilon = 0.1);
    }

    #[test]
    fn test_variance_scaling_initialization() {
        let mut rng = StdRng::seed_from_u64(42);
        let initializer = WeightInitializer::<f64>::new(InitStrategy::VarianceScaling {
            scale: 2.0,
            mode: ScalingMode::FanIn,
            distribution: ScalingDistribution::Normal,
        });

        let weights = initializer
            .initialize_2d(&mut rng, (100, 50))
            .expect("operation should succeed");

        // Check variance
        let fan_in = 100;
        let expected_variance = 2.0 / fan_in as f64;

        let mean = weights.mean().expect("operation should succeed");
        let actual_variance = weights
            .mapv(|x| (x - mean) * (x - mean))
            .mean()
            .expect("operation should succeed");

        assert_abs_diff_eq!(mean, 0.0, epsilon = 0.1);
        assert_abs_diff_eq!(actual_variance, expected_variance, epsilon = 0.005);
    }

    #[test]
    fn test_bias_initialization() {
        let mut rng = StdRng::seed_from_u64(42);

        // Test zeros bias initialization (default for most strategies)
        let initializer = WeightInitializer::<f64>::xavier_uniform();
        let biases = initializer
            .initialize_1d(&mut rng, 10)
            .expect("operation should succeed");

        for &val in biases.iter() {
            assert_eq!(val, 0.0);
        }

        // Test custom bias initialization
        let initializer = WeightInitializer::<f64>::uniform(-0.1, 0.1);
        let biases = initializer
            .initialize_1d(&mut rng, 10)
            .expect("operation should succeed");

        for &val in biases.iter() {
            assert!((-0.1..=0.1).contains(&val));
        }
    }
}