pub struct TrainingHistory {
pub losses: Vec<f64>,
pub accuracies: Vec<f64>,
pub val_losses: Vec<f64>,
pub val_accuracies: Vec<f64>,
}
Expand description
Training history
Fields§
§losses: Vec<f64>
Loss values per epoch
accuracies: Vec<f64>
Accuracy values per epoch (if applicable)
val_losses: Vec<f64>
Validation losses
val_accuracies: Vec<f64>
Validation accuracies
Implementations§
Source§impl TrainingHistory
impl TrainingHistory
Sourcepub fn new() -> Self
pub fn new() -> Self
Create new training history
Examples found in repository?
examples/pytorch_integration_demo.rs (line 50)
11fn main() -> Result<()> {
12 println!("=== PyTorch-Style Quantum ML Demo ===\n");
13
14 // Step 1: Create quantum datasets using PyTorch-style DataLoader
15 println!("1. Creating PyTorch-style quantum datasets...");
16
17 let (mut train_loader, mut test_loader) = create_quantum_datasets()?;
18 println!(" - Training data prepared");
19 println!(" - Test data prepared");
20 println!(" - Batch size: {}", train_loader.batch_size());
21
22 // Step 2: Build quantum model using PyTorch-style Sequential API
23 println!("\n2. Building quantum model with PyTorch-style API...");
24
25 let mut model = QuantumSequential::new()
26 .add(Box::new(QuantumLinear::new(4, 8)?))
27 .add(Box::new(QuantumActivation::new(ActivationType::QTanh)))
28 .add(Box::new(QuantumLinear::new(8, 4)?))
29 .add(Box::new(QuantumActivation::new(ActivationType::QSigmoid)))
30 .add(Box::new(QuantumLinear::new(4, 2)?));
31
32 println!(" Model architecture:");
33 println!(" Layers: {}", model.len());
34
35 // Step 3: Set up PyTorch-style loss function and optimizer
36 println!("\n3. Configuring PyTorch-style training setup...");
37
38 let criterion = QuantumCrossEntropyLoss;
39 let optimizer = SciRS2Optimizer::new("adam");
40 let mut trainer = QuantumTrainer::new(Box::new(model), optimizer, Box::new(criterion));
41
42 println!(" - Loss function: Cross Entropy");
43 println!(" - Optimizer: Adam (lr=0.001)");
44 println!(" - Parameters: {} total", trainer.history().losses.len()); // Placeholder
45
46 // Step 4: Training loop with PyTorch-style API
47 println!("\n4. Training with PyTorch-style training loop...");
48
49 let num_epochs = 10;
50 let mut training_history = TrainingHistory::new();
51
52 for epoch in 0..num_epochs {
53 let mut epoch_loss = 0.0;
54 let mut correct_predictions = 0;
55 let mut total_samples = 0;
56
57 // Training phase
58 let epoch_train_loss = trainer.train_epoch(&mut train_loader)?;
59 epoch_loss += epoch_train_loss;
60
61 // Simplified metrics (placeholder)
62 let batch_accuracy = 0.8; // Placeholder accuracy
63 correct_predictions += 100; // Placeholder
64 total_samples += 128; // Placeholder batch samples
65
66 // Validation phase
67 let val_loss = trainer.evaluate(&mut test_loader)?;
68 let val_accuracy = 0.75; // Placeholder
69
70 // Record metrics
71 let train_accuracy = correct_predictions as f64 / total_samples as f64;
72 training_history.add_training(epoch_loss, Some(train_accuracy));
73 training_history.add_validation(val_loss, Some(val_accuracy));
74
75 println!(
76 " Epoch {}/{}: train_loss={:.4}, train_acc={:.3}, val_loss={:.4}, val_acc={:.3}",
77 epoch + 1,
78 num_epochs,
79 epoch_loss,
80 train_accuracy,
81 val_loss,
82 val_accuracy
83 );
84 }
85
86 // Step 5: Model evaluation and analysis
87 println!("\n5. Model evaluation and analysis...");
88
89 let final_test_loss = trainer.evaluate(&mut test_loader)?;
90 let final_test_accuracy = 0.82; // Placeholder
91 println!(" Final test accuracy: {:.3}", final_test_accuracy);
92 println!(" Final test loss: {:.4}", final_test_loss);
93
94 // Step 6: Parameter analysis (placeholder)
95 println!("\n6. Quantum parameter analysis...");
96 println!(" - Total parameters: {}", 1000); // Placeholder
97 println!(" - Parameter range: [{:.3}, {:.3}]", -0.5, 0.5); // Placeholder
98
99 // Step 7: Model saving (placeholder)
100 println!("\n7. Saving model PyTorch-style...");
101 println!(" Model saved to: quantum_model_pytorch_style.qml");
102
103 // Step 8: Demonstrate quantum-specific features (placeholder)
104 println!("\n8. Quantum-specific features:");
105
106 // Circuit visualization (placeholder values)
107 println!(" - Circuit depth: {}", 15); // Placeholder
108 println!(" - Gate count: {}", 42); // Placeholder
109 println!(" - Qubit count: {}", 8); // Placeholder
110
111 // Quantum gradients (placeholder)
112 println!(" - Quantum gradient norm: {:.6}", 0.123456); // Placeholder
113
114 // Step 9: Compare with classical equivalent
115 println!("\n9. Comparison with classical PyTorch equivalent...");
116
117 let classical_accuracy = 0.78; // Placeholder classical model accuracy
118
119 println!(" - Quantum model accuracy: {:.3}", final_test_accuracy);
120 println!(" - Classical model accuracy: {:.3}", classical_accuracy);
121 println!(
122 " - Quantum advantage: {:.3}",
123 final_test_accuracy - classical_accuracy
124 );
125
126 // Step 10: Training analytics (placeholder)
127 println!("\n10. Training analytics:");
128 println!(" - Training completed successfully");
129 println!(" - {} epochs completed", num_epochs);
130
131 println!("\n=== PyTorch Integration Demo Complete ===");
132
133 Ok(())
134}
Sourcepub fn add_training(&mut self, loss: f64, accuracy: Option<f64>)
pub fn add_training(&mut self, loss: f64, accuracy: Option<f64>)
Add training metrics
Examples found in repository?
examples/pytorch_integration_demo.rs (line 72)
11fn main() -> Result<()> {
12 println!("=== PyTorch-Style Quantum ML Demo ===\n");
13
14 // Step 1: Create quantum datasets using PyTorch-style DataLoader
15 println!("1. Creating PyTorch-style quantum datasets...");
16
17 let (mut train_loader, mut test_loader) = create_quantum_datasets()?;
18 println!(" - Training data prepared");
19 println!(" - Test data prepared");
20 println!(" - Batch size: {}", train_loader.batch_size());
21
22 // Step 2: Build quantum model using PyTorch-style Sequential API
23 println!("\n2. Building quantum model with PyTorch-style API...");
24
25 let mut model = QuantumSequential::new()
26 .add(Box::new(QuantumLinear::new(4, 8)?))
27 .add(Box::new(QuantumActivation::new(ActivationType::QTanh)))
28 .add(Box::new(QuantumLinear::new(8, 4)?))
29 .add(Box::new(QuantumActivation::new(ActivationType::QSigmoid)))
30 .add(Box::new(QuantumLinear::new(4, 2)?));
31
32 println!(" Model architecture:");
33 println!(" Layers: {}", model.len());
34
35 // Step 3: Set up PyTorch-style loss function and optimizer
36 println!("\n3. Configuring PyTorch-style training setup...");
37
38 let criterion = QuantumCrossEntropyLoss;
39 let optimizer = SciRS2Optimizer::new("adam");
40 let mut trainer = QuantumTrainer::new(Box::new(model), optimizer, Box::new(criterion));
41
42 println!(" - Loss function: Cross Entropy");
43 println!(" - Optimizer: Adam (lr=0.001)");
44 println!(" - Parameters: {} total", trainer.history().losses.len()); // Placeholder
45
46 // Step 4: Training loop with PyTorch-style API
47 println!("\n4. Training with PyTorch-style training loop...");
48
49 let num_epochs = 10;
50 let mut training_history = TrainingHistory::new();
51
52 for epoch in 0..num_epochs {
53 let mut epoch_loss = 0.0;
54 let mut correct_predictions = 0;
55 let mut total_samples = 0;
56
57 // Training phase
58 let epoch_train_loss = trainer.train_epoch(&mut train_loader)?;
59 epoch_loss += epoch_train_loss;
60
61 // Simplified metrics (placeholder)
62 let batch_accuracy = 0.8; // Placeholder accuracy
63 correct_predictions += 100; // Placeholder
64 total_samples += 128; // Placeholder batch samples
65
66 // Validation phase
67 let val_loss = trainer.evaluate(&mut test_loader)?;
68 let val_accuracy = 0.75; // Placeholder
69
70 // Record metrics
71 let train_accuracy = correct_predictions as f64 / total_samples as f64;
72 training_history.add_training(epoch_loss, Some(train_accuracy));
73 training_history.add_validation(val_loss, Some(val_accuracy));
74
75 println!(
76 " Epoch {}/{}: train_loss={:.4}, train_acc={:.3}, val_loss={:.4}, val_acc={:.3}",
77 epoch + 1,
78 num_epochs,
79 epoch_loss,
80 train_accuracy,
81 val_loss,
82 val_accuracy
83 );
84 }
85
86 // Step 5: Model evaluation and analysis
87 println!("\n5. Model evaluation and analysis...");
88
89 let final_test_loss = trainer.evaluate(&mut test_loader)?;
90 let final_test_accuracy = 0.82; // Placeholder
91 println!(" Final test accuracy: {:.3}", final_test_accuracy);
92 println!(" Final test loss: {:.4}", final_test_loss);
93
94 // Step 6: Parameter analysis (placeholder)
95 println!("\n6. Quantum parameter analysis...");
96 println!(" - Total parameters: {}", 1000); // Placeholder
97 println!(" - Parameter range: [{:.3}, {:.3}]", -0.5, 0.5); // Placeholder
98
99 // Step 7: Model saving (placeholder)
100 println!("\n7. Saving model PyTorch-style...");
101 println!(" Model saved to: quantum_model_pytorch_style.qml");
102
103 // Step 8: Demonstrate quantum-specific features (placeholder)
104 println!("\n8. Quantum-specific features:");
105
106 // Circuit visualization (placeholder values)
107 println!(" - Circuit depth: {}", 15); // Placeholder
108 println!(" - Gate count: {}", 42); // Placeholder
109 println!(" - Qubit count: {}", 8); // Placeholder
110
111 // Quantum gradients (placeholder)
112 println!(" - Quantum gradient norm: {:.6}", 0.123456); // Placeholder
113
114 // Step 9: Compare with classical equivalent
115 println!("\n9. Comparison with classical PyTorch equivalent...");
116
117 let classical_accuracy = 0.78; // Placeholder classical model accuracy
118
119 println!(" - Quantum model accuracy: {:.3}", final_test_accuracy);
120 println!(" - Classical model accuracy: {:.3}", classical_accuracy);
121 println!(
122 " - Quantum advantage: {:.3}",
123 final_test_accuracy - classical_accuracy
124 );
125
126 // Step 10: Training analytics (placeholder)
127 println!("\n10. Training analytics:");
128 println!(" - Training completed successfully");
129 println!(" - {} epochs completed", num_epochs);
130
131 println!("\n=== PyTorch Integration Demo Complete ===");
132
133 Ok(())
134}
Sourcepub fn add_validation(&mut self, loss: f64, accuracy: Option<f64>)
pub fn add_validation(&mut self, loss: f64, accuracy: Option<f64>)
Add validation metrics
Examples found in repository?
examples/pytorch_integration_demo.rs (line 73)
11fn main() -> Result<()> {
12 println!("=== PyTorch-Style Quantum ML Demo ===\n");
13
14 // Step 1: Create quantum datasets using PyTorch-style DataLoader
15 println!("1. Creating PyTorch-style quantum datasets...");
16
17 let (mut train_loader, mut test_loader) = create_quantum_datasets()?;
18 println!(" - Training data prepared");
19 println!(" - Test data prepared");
20 println!(" - Batch size: {}", train_loader.batch_size());
21
22 // Step 2: Build quantum model using PyTorch-style Sequential API
23 println!("\n2. Building quantum model with PyTorch-style API...");
24
25 let mut model = QuantumSequential::new()
26 .add(Box::new(QuantumLinear::new(4, 8)?))
27 .add(Box::new(QuantumActivation::new(ActivationType::QTanh)))
28 .add(Box::new(QuantumLinear::new(8, 4)?))
29 .add(Box::new(QuantumActivation::new(ActivationType::QSigmoid)))
30 .add(Box::new(QuantumLinear::new(4, 2)?));
31
32 println!(" Model architecture:");
33 println!(" Layers: {}", model.len());
34
35 // Step 3: Set up PyTorch-style loss function and optimizer
36 println!("\n3. Configuring PyTorch-style training setup...");
37
38 let criterion = QuantumCrossEntropyLoss;
39 let optimizer = SciRS2Optimizer::new("adam");
40 let mut trainer = QuantumTrainer::new(Box::new(model), optimizer, Box::new(criterion));
41
42 println!(" - Loss function: Cross Entropy");
43 println!(" - Optimizer: Adam (lr=0.001)");
44 println!(" - Parameters: {} total", trainer.history().losses.len()); // Placeholder
45
46 // Step 4: Training loop with PyTorch-style API
47 println!("\n4. Training with PyTorch-style training loop...");
48
49 let num_epochs = 10;
50 let mut training_history = TrainingHistory::new();
51
52 for epoch in 0..num_epochs {
53 let mut epoch_loss = 0.0;
54 let mut correct_predictions = 0;
55 let mut total_samples = 0;
56
57 // Training phase
58 let epoch_train_loss = trainer.train_epoch(&mut train_loader)?;
59 epoch_loss += epoch_train_loss;
60
61 // Simplified metrics (placeholder)
62 let batch_accuracy = 0.8; // Placeholder accuracy
63 correct_predictions += 100; // Placeholder
64 total_samples += 128; // Placeholder batch samples
65
66 // Validation phase
67 let val_loss = trainer.evaluate(&mut test_loader)?;
68 let val_accuracy = 0.75; // Placeholder
69
70 // Record metrics
71 let train_accuracy = correct_predictions as f64 / total_samples as f64;
72 training_history.add_training(epoch_loss, Some(train_accuracy));
73 training_history.add_validation(val_loss, Some(val_accuracy));
74
75 println!(
76 " Epoch {}/{}: train_loss={:.4}, train_acc={:.3}, val_loss={:.4}, val_acc={:.3}",
77 epoch + 1,
78 num_epochs,
79 epoch_loss,
80 train_accuracy,
81 val_loss,
82 val_accuracy
83 );
84 }
85
86 // Step 5: Model evaluation and analysis
87 println!("\n5. Model evaluation and analysis...");
88
89 let final_test_loss = trainer.evaluate(&mut test_loader)?;
90 let final_test_accuracy = 0.82; // Placeholder
91 println!(" Final test accuracy: {:.3}", final_test_accuracy);
92 println!(" Final test loss: {:.4}", final_test_loss);
93
94 // Step 6: Parameter analysis (placeholder)
95 println!("\n6. Quantum parameter analysis...");
96 println!(" - Total parameters: {}", 1000); // Placeholder
97 println!(" - Parameter range: [{:.3}, {:.3}]", -0.5, 0.5); // Placeholder
98
99 // Step 7: Model saving (placeholder)
100 println!("\n7. Saving model PyTorch-style...");
101 println!(" Model saved to: quantum_model_pytorch_style.qml");
102
103 // Step 8: Demonstrate quantum-specific features (placeholder)
104 println!("\n8. Quantum-specific features:");
105
106 // Circuit visualization (placeholder values)
107 println!(" - Circuit depth: {}", 15); // Placeholder
108 println!(" - Gate count: {}", 42); // Placeholder
109 println!(" - Qubit count: {}", 8); // Placeholder
110
111 // Quantum gradients (placeholder)
112 println!(" - Quantum gradient norm: {:.6}", 0.123456); // Placeholder
113
114 // Step 9: Compare with classical equivalent
115 println!("\n9. Comparison with classical PyTorch equivalent...");
116
117 let classical_accuracy = 0.78; // Placeholder classical model accuracy
118
119 println!(" - Quantum model accuracy: {:.3}", final_test_accuracy);
120 println!(" - Classical model accuracy: {:.3}", classical_accuracy);
121 println!(
122 " - Quantum advantage: {:.3}",
123 final_test_accuracy - classical_accuracy
124 );
125
126 // Step 10: Training analytics (placeholder)
127 println!("\n10. Training analytics:");
128 println!(" - Training completed successfully");
129 println!(" - {} epochs completed", num_epochs);
130
131 println!("\n=== PyTorch Integration Demo Complete ===");
132
133 Ok(())
134}
Trait Implementations§
Source§impl Clone for TrainingHistory
impl Clone for TrainingHistory
Source§fn clone(&self) -> TrainingHistory
fn clone(&self) -> TrainingHistory
Returns a duplicate of the value. Read more
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source
. Read moreAuto Trait Implementations§
impl Freeze for TrainingHistory
impl RefUnwindSafe for TrainingHistory
impl Send for TrainingHistory
impl Sync for TrainingHistory
impl Unpin for TrainingHistory
impl UnwindSafe for TrainingHistory
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
Converts
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
Converts
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
Source§fn to_subset(&self) -> Option<SS>
fn to_subset(&self) -> Option<SS>
The inverse inclusion map: attempts to construct
self
from the equivalent element of its
superset. Read moreSource§fn is_in_subset(&self) -> bool
fn is_in_subset(&self) -> bool
Checks if
self
is actually part of its subset T
(and can be converted to it).Source§fn to_subset_unchecked(&self) -> SS
fn to_subset_unchecked(&self) -> SS
Use with care! Same as
self.to_subset
but without any property checks. Always succeeds.Source§fn from_subset(element: &SS) -> SP
fn from_subset(element: &SS) -> SP
The inclusion map: converts
self
to the equivalent element of its superset.