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
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
//! Model Visualization Utilities
//!
//! This module provides comprehensive visualization capabilities for neural networks,
//! including architecture diagrams, training metrics, attention heatmaps, and
//! weight distributions.

use crate::NeuralResult;
use scirs2_core::ndarray::{Array2, Array3};
use sklears_core::error::SklearsError;
use sklears_core::types::FloatBounds;
use std::collections::HashMap;
use std::fs::File;
use std::io::Write;

/// Configuration for visualization output
#[derive(Debug, Clone)]
pub struct VisualizationConfig {
    /// Output directory for visualizations
    pub output_dir: String,
    /// Image format (SVG, PNG, etc.)
    pub format: ImageFormat,
    /// Color scheme
    pub color_scheme: ColorScheme,
    /// DPI for raster formats
    pub dpi: u32,
    /// Whether to show layer names
    pub show_layer_names: bool,
    /// Whether to show tensor shapes
    pub show_tensor_shapes: bool,
}

impl Default for VisualizationConfig {
    fn default() -> Self {
        Self {
            output_dir: "./visualizations".to_string(),
            format: ImageFormat::SVG,
            color_scheme: ColorScheme::Default,
            dpi: 300,
            show_layer_names: true,
            show_tensor_shapes: true,
        }
    }
}

/// Supported image formats
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ImageFormat {
    /// Scalable Vector Graphics — lossless, suitable for diagrams
    SVG,
    /// Portable Network Graphics — raster format (SVG is generated first, then converted externally)
    PNG,
    /// Interactive HTML with embedded JavaScript visualizations
    HTML,
}

/// Color schemes for visualizations
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ColorScheme {
    /// Default color scheme
    Default,
    /// Perceptually uniform sequential color map
    Viridis,
    /// High-contrast sequential color map
    Plasma,
    /// Black-to-white grayscale ramp
    Grayscale,
}

/// Model architecture visualizer
pub struct ModelVisualizer {
    config: VisualizationConfig,
}

impl ModelVisualizer {
    /// Create a new model visualizer
    pub fn new(config: VisualizationConfig) -> Self {
        Self { config }
    }

    /// Generate a model architecture diagram
    pub fn visualize_architecture(&self, layers: &[LayerInfo], filename: &str) -> NeuralResult<()> {
        let output_path = format!(
            "{}/{}.{}",
            self.config.output_dir,
            filename,
            self.format_extension()
        );

        match self.config.format {
            ImageFormat::SVG => self.generate_svg_architecture(layers, &output_path),
            ImageFormat::HTML => self.generate_html_architecture(layers, &output_path),
            ImageFormat::PNG => {
                // For PNG, we'll generate SVG first then mention it needs conversion
                self.generate_svg_architecture(layers, &output_path.replace(".png", ".svg"))?;
                println!("SVG generated. Use external tool to convert to PNG if needed.");
                Ok(())
            }
        }
    }

    /// Generate SVG architecture diagram
    fn generate_svg_architecture(
        &self,
        layers: &[LayerInfo],
        output_path: &str,
    ) -> NeuralResult<()> {
        let mut svg = String::new();

        // SVG header
        svg.push_str(&format!(
            "<svg width=\"800\" height=\"{}\" xmlns=\"http://www.w3.org/2000/svg\">\n            <defs>\n                <style>\n                    .layer-box {{ fill: #e1f5fe; stroke: #0277bd; stroke-width: 2; }}\n                    .layer-text {{ font-family: Arial, sans-serif; font-size: 12px; text-anchor: middle; }}\n                    .layer-name {{ font-weight: bold; }}\n                    .layer-shape {{ font-size: 10px; fill: #666; }}\n                    .connection {{ stroke: #424242; stroke-width: 2; marker-end: url(#arrowhead); }}\n                </style>\n                <marker id=\"arrowhead\" markerWidth=\"10\" markerHeight=\"7\" \n                    refX=\"10\" refY=\"3.5\" orient=\"auto\">\n                    <polygon points=\"0,0 10,3.5 0,7\" fill=\"#424242\" />\n                </marker>\n            </defs>\n            ", 
            layers.len() * 100 + 100
        ));

        // Draw layers
        for (i, layer) in layers.iter().enumerate() {
            let y = i * 100 + 50;
            let x = 400;

            // Layer box
            svg.push_str(&format!(
                r#"<rect x="{}" y="{}" width="200" height="60" class="layer-box" />
                "#,
                x - 100,
                y - 30
            ));

            // Layer name
            if self.config.show_layer_names {
                svg.push_str(&format!(
                    r#"<text x="{}" y="{}" class="layer-text layer-name">{}</text>
                    "#,
                    x,
                    y - 10,
                    layer.name
                ));
            }

            // Layer type
            svg.push_str(&format!(
                r#"<text x="{}" y="{}" class="layer-text">{}</text>
                "#,
                x,
                y + 5,
                layer.layer_type
            ));

            // Shape information
            if self.config.show_tensor_shapes {
                svg.push_str(&format!(
                    r#"<text x="{}" y="{}" class="layer-text layer-shape">{:?}</text>
                    "#,
                    x,
                    y + 20,
                    layer.output_shape
                ));
            }

            // Connection to next layer
            if i < layers.len() - 1 {
                svg.push_str(&format!(
                    r#"<line x1="{}" y1="{}" x2="{}" y2="{}" class="connection" />
                    "#,
                    x,
                    y + 30,
                    x,
                    y + 70
                ));
            }
        }

        svg.push_str("</svg>");

        // Write to file
        let mut file = File::create(output_path)
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to create file: {}", e)))?;
        file.write_all(svg.as_bytes())
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to write file: {}", e)))?;

        Ok(())
    }

    /// Generate HTML architecture diagram with interactive features
    fn generate_html_architecture(
        &self,
        layers: &[LayerInfo],
        output_path: &str,
    ) -> NeuralResult<()> {
        let mut html = String::new();

        html.push_str(
            r#"
        <!DOCTYPE html>
        <html>
        <head>
            <title>Neural Network Architecture</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; }
                .architecture { display: flex; flex-direction: column; align-items: center; }
                .layer { 
                    background: #e1f5fe; 
                    border: 2px solid #0277bd; 
                    border-radius: 8px;
                    padding: 15px; 
                    margin: 10px;
                    min-width: 200px;
                    text-align: center;
                    transition: all 0.3s ease;
                }
                .layer:hover { 
                    background: #b3e5fc; 
                    transform: scale(1.05);
                    box-shadow: 0 4px 8px rgba(0,0,0,0.2);
                }
                .layer-name { font-weight: bold; font-size: 16px; color: #0277bd; }
                .layer-type { font-size: 14px; color: #424242; margin: 5px 0; }
                .layer-shape { font-size: 12px; color: #666; }
                .arrow { 
                    font-size: 24px; 
                    color: #424242; 
                    margin: 5px 0;
                }
                .layer-details {
                    display: none;
                    margin-top: 10px;
                    padding: 10px;
                    background: #f5f5f5;
                    border-radius: 4px;
                    font-size: 12px;
                }
            </style>
            <script>
                function toggleDetails(layerId) {
                    const details = document.getElementById(layerId);
                    details.style.display = details.style.display === 'none' ? 'block' : 'none';
                }
            </script>
        </head>
        <body>
            <h1>Neural Network Architecture</h1>
            <div class="architecture">
        "#,
        );

        for (i, layer) in layers.iter().enumerate() {
            html.push_str(&format!(
                r#"
                <div class="layer" onclick="toggleDetails('details_{}')">
                    <div class="layer-name">{}</div>
                    <div class="layer-type">{}</div>
                    <div class="layer-shape">Shape: {:?}</div>
                    <div id="details_{}" class="layer-details">
                        <strong>Parameters:</strong> {}<br>
                        <strong>Activation:</strong> {}<br>
                        <strong>Trainable:</strong> {}
                    </div>
                </div>
                "#,
                i,
                layer.name,
                layer.layer_type,
                layer.output_shape,
                i,
                layer.num_parameters,
                layer.activation.as_deref().unwrap_or("None"),
                layer.trainable
            ));

            if i < layers.len() - 1 {
                html.push_str(r#"<div class="arrow">↓</div>"#);
            }
        }

        html.push_str(
            r#"
            </div>
        </body>
        </html>
        "#,
        );

        // Write to file
        let mut file = File::create(output_path)
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to create file: {}", e)))?;
        file.write_all(html.as_bytes())
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to write file: {}", e)))?;

        Ok(())
    }

    /// Get file extension for current format
    fn format_extension(&self) -> &'static str {
        match self.config.format {
            ImageFormat::SVG => "svg",
            ImageFormat::PNG => "png",
            ImageFormat::HTML => "html",
        }
    }
}

/// Information about a layer for visualization
#[derive(Debug, Clone)]
pub struct LayerInfo {
    /// Human-readable name identifying this layer in the architecture diagram
    pub name: String,
    /// String descriptor of the layer class (e.g., `"Dense"`, `"Conv2D"`)
    pub layer_type: String,
    /// Shape of the output tensor produced by this layer
    pub output_shape: Vec<usize>,
    /// Total number of trainable parameters in this layer
    pub num_parameters: usize,
    /// Name of the activation function applied after this layer, if any
    pub activation: Option<String>,
    /// Whether the layer's parameters are updated during training
    pub trainable: bool,
}

/// Training metrics visualizer
pub struct TrainingVisualizer {
    config: VisualizationConfig,
}

impl TrainingVisualizer {
    /// Create a new training visualizer
    pub fn new(config: VisualizationConfig) -> Self {
        Self { config }
    }

    /// Plot training history (loss, accuracy, etc.)
    pub fn plot_training_history(
        &self,
        metrics: &TrainingMetrics,
        filename: &str,
    ) -> NeuralResult<()> {
        let output_path = format!("{}/{}.html", self.config.output_dir, filename);

        let mut html = String::new();
        html.push_str(
            r#"
        <!DOCTYPE html>
        <html>
        <head>
            <title>Training History</title>
            <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; }
                .plot-container { width: 100%; height: 400px; margin: 20px 0; }
            </style>
        </head>
        <body>
            <h1>Training History</h1>
        "#,
        );

        // Loss plot
        html.push_str(r#"<div id="loss-plot" class="plot-container"></div>"#);
        html.push_str(&format!(
            r#"
        <script>
            var lossData = [{{
                x: [{}],
                y: [{}],
                type: 'scatter',
                mode: 'lines',
                name: 'Training Loss',
                line: {{color: '#1f77b4'}}
            }}
        "#,
            (0..metrics.train_loss.len())
                .map(|i| i.to_string())
                .collect::<Vec<_>>()
                .join(","),
            metrics
                .train_loss
                .iter()
                .map(|x| x.to_string())
                .collect::<Vec<_>>()
                .join(",")
        ));

        if !metrics.val_loss.is_empty() {
            html.push_str(&format!(
                r#",{{
                x: [{}],
                y: [{}],
                type: 'scatter',
                mode: 'lines',
                name: 'Validation Loss',
                line: {{color: '#ff7f0e'}}
            }}"#,
                (0..metrics.val_loss.len())
                    .map(|i| i.to_string())
                    .collect::<Vec<_>>()
                    .join(","),
                metrics
                    .val_loss
                    .iter()
                    .map(|x| x.to_string())
                    .collect::<Vec<_>>()
                    .join(",")
            ));
        }

        html.push_str(
            r#"];
            var lossLayout = {
                title: 'Training Loss',
                xaxis: { title: 'Epoch' },
                yaxis: { title: 'Loss' }
            };
            Plotly.newPlot('loss-plot', lossData, lossLayout);
        </script>
        "#,
        );

        // Accuracy plot (if available)
        if !metrics.train_accuracy.is_empty() {
            html.push_str(r#"<div id="accuracy-plot" class="plot-container"></div>"#);
            html.push_str(&format!(
                r#"
            <script>
                var accuracyData = [{{
                    x: [{}],
                    y: [{}],
                    type: 'scatter',
                    mode: 'lines',
                    name: 'Training Accuracy',
                    line: {{color: '#2ca02c'}}
                }}
            "#,
                (0..metrics.train_accuracy.len())
                    .map(|i| i.to_string())
                    .collect::<Vec<_>>()
                    .join(","),
                metrics
                    .train_accuracy
                    .iter()
                    .map(|x| x.to_string())
                    .collect::<Vec<_>>()
                    .join(",")
            ));

            if !metrics.val_accuracy.is_empty() {
                html.push_str(&format!(
                    r#",{{
                    x: [{}],
                    y: [{}],
                    type: 'scatter',
                    mode: 'lines',
                    name: 'Validation Accuracy',
                    line: {{color: '#d62728'}}
                }}"#,
                    (0..metrics.val_accuracy.len())
                        .map(|i| i.to_string())
                        .collect::<Vec<_>>()
                        .join(","),
                    metrics
                        .val_accuracy
                        .iter()
                        .map(|x| x.to_string())
                        .collect::<Vec<_>>()
                        .join(",")
                ));
            }

            html.push_str(
                r#"];
                var accuracyLayout = {
                    title: 'Training Accuracy',
                    xaxis: { title: 'Epoch' },
                    yaxis: { title: 'Accuracy' }
                };
                Plotly.newPlot('accuracy-plot', accuracyData, accuracyLayout);
            </script>
            "#,
            );
        }

        html.push_str(
            r#"
        </body>
        </html>
        "#,
        );

        // Write to file
        let mut file = File::create(&output_path)
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to create file: {}", e)))?;
        file.write_all(html.as_bytes())
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to write file: {}", e)))?;

        println!("Training history saved to: {}", output_path);
        Ok(())
    }
}

/// Training metrics for visualization
#[derive(Debug, Clone, Default)]
pub struct TrainingMetrics {
    /// Per-epoch training loss values
    pub train_loss: Vec<f64>,
    /// Per-epoch validation loss values
    pub val_loss: Vec<f64>,
    /// Per-epoch training accuracy values
    pub train_accuracy: Vec<f64>,
    /// Per-epoch validation accuracy values
    pub val_accuracy: Vec<f64>,
    /// Learning rate schedule over epochs
    pub learning_rates: Vec<f64>,
}

/// Attention heatmap visualizer
pub struct AttentionVisualizer {
    config: VisualizationConfig,
}

impl AttentionVisualizer {
    /// Create a new attention visualizer
    pub fn new(config: VisualizationConfig) -> Self {
        Self { config }
    }

    /// Generate attention heatmap visualization
    pub fn visualize_attention_weights<T: FloatBounds>(
        &self,
        attention_weights: &Array3<T>,
        tokens: &[String],
        filename: &str,
    ) -> NeuralResult<()> {
        let output_path = format!("{}/{}.html", self.config.output_dir, filename);

        let mut html = String::new();
        html.push_str(
            r#"
        <!DOCTYPE html>
        <html>
        <head>
            <title>Attention Heatmap</title>
            <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; }
                .heatmap-container { width: 100%; height: 600px; margin: 20px 0; }
            </style>
        </head>
        <body>
            <h1>Attention Weights Heatmap</h1>
            <div id="heatmap" class="heatmap-container"></div>
            <script>
        "#,
        );

        // Get the first head of the first layer for visualization
        let (batch_size, seq_len, _) = attention_weights.dim();
        if batch_size > 0 && seq_len > 0 {
            // Convert attention weights to JavaScript format
            let mut weights_js = String::new();
            weights_js.push('[');
            for i in 0..seq_len {
                weights_js.push('[');
                for j in 0..seq_len {
                    if j > 0 {
                        weights_js.push(',');
                    }
                    weights_js.push_str(
                        &attention_weights[[0, i, j]]
                            .to_f64()
                            .unwrap_or(0.0)
                            .to_string(),
                    );
                }
                weights_js.push(']');
                if i < seq_len - 1 {
                    weights_js.push(',');
                }
            }
            weights_js.push(']');

            // Convert tokens to JavaScript format
            let tokens_js = format!("[\"{}\"]", tokens.join("\",\""));

            html.push_str(&format!(
                r#"
                var data = [{{
                    z: {},
                    x: {},
                    y: {},
                    type: 'heatmap',
                    colorscale: 'Viridis'
                }}];
                
                var layout = {{
                    title: 'Attention Weights',
                    xaxis: {{ title: 'Key Tokens' }},
                    yaxis: {{ title: 'Query Tokens' }}
                }};
                
                Plotly.newPlot('heatmap', data, layout);
            "#,
                weights_js, tokens_js, tokens_js
            ));
        }

        html.push_str(
            r#"
            </script>
        </body>
        </html>
        "#,
        );

        // Write to file
        let mut file = File::create(&output_path)
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to create file: {}", e)))?;
        file.write_all(html.as_bytes())
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to write file: {}", e)))?;

        println!("Attention heatmap saved to: {}", output_path);
        Ok(())
    }
}

/// Weight distribution visualizer
pub struct WeightVisualizer {
    config: VisualizationConfig,
}

impl WeightVisualizer {
    /// Create a new weight visualizer
    pub fn new(config: VisualizationConfig) -> Self {
        Self { config }
    }

    /// Visualize weight distributions across layers
    pub fn visualize_weight_distributions<T: FloatBounds>(
        &self,
        weights: &HashMap<String, Array2<T>>,
        filename: &str,
    ) -> NeuralResult<()> {
        let output_path = format!("{}/{}.html", self.config.output_dir, filename);

        let mut html = String::new();
        html.push_str(
            r#"
        <!DOCTYPE html>
        <html>
        <head>
            <title>Weight Distributions</title>
            <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; }
                .histogram-container { width: 100%; height: 400px; margin: 20px 0; }
            </style>
        </head>
        <body>
            <h1>Weight Distributions</h1>
        "#,
        );

        for (layer_name, weight_matrix) in weights.iter() {
            let div_id = format!("histogram-{}", layer_name.replace(".", "-"));
            html.push_str(&format!(r#"<h2>{}</h2>"#, layer_name));
            html.push_str(&format!(
                r#"<div id="{}" class="histogram-container"></div>"#,
                div_id
            ));

            // Flatten weights and convert to JavaScript array
            let flattened: Vec<f64> = weight_matrix
                .iter()
                .map(|&w| w.to_f64().unwrap_or(0.0))
                .collect();

            let weights_js = format!(
                "[{}]",
                flattened
                    .iter()
                    .map(|x| x.to_string())
                    .collect::<Vec<_>>()
                    .join(",")
            );

            html.push_str(&format!(
                r#"
            <script>
                var data_{} = [{{
                    x: {},
                    type: 'histogram',
                    nbinsx: 50,
                    name: '{}'
                }}];
                
                var layout_{} = {{
                    title: '{} Weight Distribution',
                    xaxis: {{ title: 'Weight Value' }},
                    yaxis: {{ title: 'Frequency' }}
                }};
                
                Plotly.newPlot('{}', data_{}, layout_{});
            </script>
            "#,
                div_id, weights_js, layer_name, div_id, layer_name, div_id, div_id, div_id
            ));
        }

        html.push_str(
            r#"
        </body>
        </html>
        "#,
        );

        // Write to file
        let mut file = File::create(&output_path)
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to create file: {}", e)))?;
        file.write_all(html.as_bytes())
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to write file: {}", e)))?;

        println!("Weight distributions saved to: {}", output_path);
        Ok(())
    }
}

/// Create output directory if it doesn't exist
pub fn ensure_output_directory(path: &str) -> NeuralResult<()> {
    std::fs::create_dir_all(path)
        .map_err(|e| SklearsError::InvalidInput(format!("Failed to create directory: {}", e)))
}

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

    #[test]
    fn test_visualization_config_default() {
        let config = VisualizationConfig::default();
        assert_eq!(config.format, ImageFormat::SVG);
        assert_eq!(config.color_scheme, ColorScheme::Default);
        assert_eq!(config.dpi, 300);
    }

    #[test]
    fn test_layer_info_creation() {
        let layer_info = LayerInfo {
            name: "dense_1".to_string(),
            layer_type: "Dense".to_string(),
            output_shape: vec![128, 64],
            num_parameters: 8256,
            activation: Some("ReLU".to_string()),
            trainable: true,
        };

        assert_eq!(layer_info.name, "dense_1");
        assert_eq!(layer_info.num_parameters, 8256);
    }

    #[test]
    fn test_training_metrics_default() {
        let metrics = TrainingMetrics::default();
        assert!(metrics.train_loss.is_empty());
        assert!(metrics.val_loss.is_empty());
        assert!(metrics.train_accuracy.is_empty());
    }
}