pub struct QuantumBoltzmannMachine { /* private fields */ }Expand description
Quantum Boltzmann Machine
Implementations§
Source§impl QuantumBoltzmannMachine
impl QuantumBoltzmannMachine
Sourcepub fn new(
num_visible: usize,
num_hidden: usize,
temperature: f64,
learning_rate: f64,
) -> Result<Self>
pub fn new( num_visible: usize, num_hidden: usize, temperature: f64, learning_rate: f64, ) -> Result<Self>
Create a new Quantum Boltzmann Machine
Examples found in repository?
examples/quantum_boltzmann.rs (lines 40-45)
38fn basic_qbm_demo() -> Result<()> {
39 // Create a small QBM
40 let mut qbm = QuantumBoltzmannMachine::new(
41 4, // visible units
42 2, // hidden units
43 1.0, // temperature
44 0.01, // learning rate
45 )?;
46
47 println!(" Created QBM with 4 visible and 2 hidden units");
48
49 // Generate synthetic binary data
50 let data = generate_binary_patterns(100, 4);
51
52 // Train the QBM
53 println!(" Training on binary patterns...");
54 let losses = qbm.train(&data, 50, 10)?;
55
56 println!(" Training complete:");
57 println!(" - Initial loss: {:.4}", losses[0]);
58 println!(" - Final loss: {:.4}", losses.last().unwrap());
59
60 // Sample from trained model
61 let samples = qbm.sample(5)?;
62 println!("\n Generated samples:");
63 for (i, sample) in samples.outer_iter().enumerate() {
64 print!(" Sample {}: [", i + 1);
65 for val in sample.iter() {
66 print!("{:.0} ", val);
67 }
68 println!("]");
69 }
70
71 Ok(())
72}
73
74/// RBM demonstration with persistent contrastive divergence
75fn rbm_demo() -> Result<()> {
76 // Create RBM with annealing
77 let annealing = AnnealingSchedule::new(2.0, 0.5, 100);
78
79 let mut rbm = QuantumRBM::new(
80 6, // visible units
81 3, // hidden units
82 2.0, // initial temperature
83 0.01, // learning rate
84 )?
85 .with_annealing(annealing);
86
87 println!(" Created Quantum RBM with annealing schedule");
88
89 // Generate correlated binary data
90 let data = generate_correlated_data(200, 6);
91
92 // Train with PCD
93 println!(" Training with Persistent Contrastive Divergence...");
94 let losses = rbm.train_pcd(
95 &data, 100, // epochs
96 20, // batch size
97 50, // persistent chains
98 )?;
99
100 // Analyze training
101 let improvement = (losses[0] - losses.last().unwrap()) / losses[0] * 100.0;
102 println!(" Training statistics:");
103 println!(" - Loss reduction: {:.1}%", improvement);
104 println!(" - Final temperature: 0.5");
105
106 // Test reconstruction
107 let test_data = data.slice(s![0..5, ..]).to_owned();
108 let reconstructed = rbm.qbm().reconstruct(&test_data)?;
109
110 println!("\n Reconstruction quality:");
111 for i in 0..3 {
112 print!(" Original: [");
113 for val in test_data.row(i).iter() {
114 print!("{:.0} ", val);
115 }
116 print!("] → Reconstructed: [");
117 for val in reconstructed.row(i).iter() {
118 print!("{:.0} ", val);
119 }
120 println!("]");
121 }
122
123 Ok(())
124}
125
126/// Deep Boltzmann Machine demonstration
127fn deep_boltzmann_demo() -> Result<()> {
128 // Create a 3-layer DBM
129 let layer_sizes = vec![8, 4, 2];
130 let mut dbm = DeepBoltzmannMachine::new(
131 layer_sizes.clone(),
132 1.0, // temperature
133 0.01, // learning rate
134 )?;
135
136 println!(" Created Deep Boltzmann Machine:");
137 println!(" - Architecture: {:?}", layer_sizes);
138 println!(" - Total layers: {}", dbm.rbms().len());
139
140 // Generate hierarchical data
141 let data = generate_hierarchical_data(300, 8);
142
143 // Layer-wise pretraining
144 println!("\n Performing layer-wise pretraining...");
145 dbm.pretrain(
146 &data, 50, // epochs per layer
147 30, // batch size
148 )?;
149
150 println!("\n Pretraining complete!");
151 println!(" Each layer learned increasingly abstract features");
152
153 Ok(())
154}
155
156/// Energy landscape visualization
157fn energy_landscape_demo() -> Result<()> {
158 // Create small QBM for visualization
159 let qbm = QuantumBoltzmannMachine::new(
160 2, // visible units (for 2D visualization)
161 1, // hidden unit
162 0.5, // temperature
163 0.01, // learning rate
164 )?;
165
166 println!(" Analyzing energy landscape of 2-unit system");
167
168 // Compute energy for all 4 possible states
169 let states = vec![
170 Array1::from_vec(vec![0.0, 0.0]),
171 Array1::from_vec(vec![0.0, 1.0]),
172 Array1::from_vec(vec![1.0, 0.0]),
173 Array1::from_vec(vec![1.0, 1.0]),
174 ];
175
176 println!("\n State energies:");
177 for (i, state) in states.iter().enumerate() {
178 let energy = qbm.energy(state);
179 let prob = (-energy / qbm.temperature()).exp();
180 println!(
181 " State [{:.0}, {:.0}]: E = {:.3}, P ∝ {:.3}",
182 state[0], state[1], energy, prob
183 );
184 }
185
186 // Show coupling matrix
187 println!("\n Coupling matrix:");
188 for i in 0..3 {
189 print!(" [");
190 for j in 0..3 {
191 print!("{:6.3} ", qbm.couplings()[[i, j]]);
192 }
193 println!("]");
194 }
195
196 Ok(())
197}Sourcepub fn energy(&self, state: &Array1<f64>) -> f64
pub fn energy(&self, state: &Array1<f64>) -> f64
Compute energy of a configuration
Examples found in repository?
examples/quantum_boltzmann.rs (line 178)
157fn energy_landscape_demo() -> Result<()> {
158 // Create small QBM for visualization
159 let qbm = QuantumBoltzmannMachine::new(
160 2, // visible units (for 2D visualization)
161 1, // hidden unit
162 0.5, // temperature
163 0.01, // learning rate
164 )?;
165
166 println!(" Analyzing energy landscape of 2-unit system");
167
168 // Compute energy for all 4 possible states
169 let states = vec![
170 Array1::from_vec(vec![0.0, 0.0]),
171 Array1::from_vec(vec![0.0, 1.0]),
172 Array1::from_vec(vec![1.0, 0.0]),
173 Array1::from_vec(vec![1.0, 1.0]),
174 ];
175
176 println!("\n State energies:");
177 for (i, state) in states.iter().enumerate() {
178 let energy = qbm.energy(state);
179 let prob = (-energy / qbm.temperature()).exp();
180 println!(
181 " State [{:.0}, {:.0}]: E = {:.3}, P ∝ {:.3}",
182 state[0], state[1], energy, prob
183 );
184 }
185
186 // Show coupling matrix
187 println!("\n Coupling matrix:");
188 for i in 0..3 {
189 print!(" [");
190 for j in 0..3 {
191 print!("{:6.3} ", qbm.couplings()[[i, j]]);
192 }
193 println!("]");
194 }
195
196 Ok(())
197}Sourcepub fn create_gibbs_circuit(&self) -> Result<()>
pub fn create_gibbs_circuit(&self) -> Result<()>
Create quantum circuit for Gibbs state preparation
Sourcepub fn sample(&self, num_samples: usize) -> Result<Array2<f64>>
pub fn sample(&self, num_samples: usize) -> Result<Array2<f64>>
Sample from the Boltzmann distribution
Examples found in repository?
examples/quantum_boltzmann.rs (line 61)
38fn basic_qbm_demo() -> Result<()> {
39 // Create a small QBM
40 let mut qbm = QuantumBoltzmannMachine::new(
41 4, // visible units
42 2, // hidden units
43 1.0, // temperature
44 0.01, // learning rate
45 )?;
46
47 println!(" Created QBM with 4 visible and 2 hidden units");
48
49 // Generate synthetic binary data
50 let data = generate_binary_patterns(100, 4);
51
52 // Train the QBM
53 println!(" Training on binary patterns...");
54 let losses = qbm.train(&data, 50, 10)?;
55
56 println!(" Training complete:");
57 println!(" - Initial loss: {:.4}", losses[0]);
58 println!(" - Final loss: {:.4}", losses.last().unwrap());
59
60 // Sample from trained model
61 let samples = qbm.sample(5)?;
62 println!("\n Generated samples:");
63 for (i, sample) in samples.outer_iter().enumerate() {
64 print!(" Sample {}: [", i + 1);
65 for val in sample.iter() {
66 print!("{:.0} ", val);
67 }
68 println!("]");
69 }
70
71 Ok(())
72}Sourcepub fn compute_gradients(
&self,
data: &Array2<f64>,
) -> Result<(Array2<f64>, Array1<f64>)>
pub fn compute_gradients( &self, data: &Array2<f64>, ) -> Result<(Array2<f64>, Array1<f64>)>
Compute gradients using contrastive divergence
Sourcepub fn train(
&mut self,
data: &Array2<f64>,
epochs: usize,
batch_size: usize,
) -> Result<Vec<f64>>
pub fn train( &mut self, data: &Array2<f64>, epochs: usize, batch_size: usize, ) -> Result<Vec<f64>>
Train the Boltzmann machine
Examples found in repository?
examples/quantum_boltzmann.rs (line 54)
38fn basic_qbm_demo() -> Result<()> {
39 // Create a small QBM
40 let mut qbm = QuantumBoltzmannMachine::new(
41 4, // visible units
42 2, // hidden units
43 1.0, // temperature
44 0.01, // learning rate
45 )?;
46
47 println!(" Created QBM with 4 visible and 2 hidden units");
48
49 // Generate synthetic binary data
50 let data = generate_binary_patterns(100, 4);
51
52 // Train the QBM
53 println!(" Training on binary patterns...");
54 let losses = qbm.train(&data, 50, 10)?;
55
56 println!(" Training complete:");
57 println!(" - Initial loss: {:.4}", losses[0]);
58 println!(" - Final loss: {:.4}", losses.last().unwrap());
59
60 // Sample from trained model
61 let samples = qbm.sample(5)?;
62 println!("\n Generated samples:");
63 for (i, sample) in samples.outer_iter().enumerate() {
64 print!(" Sample {}: [", i + 1);
65 for val in sample.iter() {
66 print!("{:.0} ", val);
67 }
68 println!("]");
69 }
70
71 Ok(())
72}Sourcepub fn reconstruct(&self, visible: &Array2<f64>) -> Result<Array2<f64>>
pub fn reconstruct(&self, visible: &Array2<f64>) -> Result<Array2<f64>>
Reconstruct visible units
Examples found in repository?
examples/quantum_boltzmann.rs (line 108)
75fn rbm_demo() -> Result<()> {
76 // Create RBM with annealing
77 let annealing = AnnealingSchedule::new(2.0, 0.5, 100);
78
79 let mut rbm = QuantumRBM::new(
80 6, // visible units
81 3, // hidden units
82 2.0, // initial temperature
83 0.01, // learning rate
84 )?
85 .with_annealing(annealing);
86
87 println!(" Created Quantum RBM with annealing schedule");
88
89 // Generate correlated binary data
90 let data = generate_correlated_data(200, 6);
91
92 // Train with PCD
93 println!(" Training with Persistent Contrastive Divergence...");
94 let losses = rbm.train_pcd(
95 &data, 100, // epochs
96 20, // batch size
97 50, // persistent chains
98 )?;
99
100 // Analyze training
101 let improvement = (losses[0] - losses.last().unwrap()) / losses[0] * 100.0;
102 println!(" Training statistics:");
103 println!(" - Loss reduction: {:.1}%", improvement);
104 println!(" - Final temperature: 0.5");
105
106 // Test reconstruction
107 let test_data = data.slice(s![0..5, ..]).to_owned();
108 let reconstructed = rbm.qbm().reconstruct(&test_data)?;
109
110 println!("\n Reconstruction quality:");
111 for i in 0..3 {
112 print!(" Original: [");
113 for val in test_data.row(i).iter() {
114 print!("{:.0} ", val);
115 }
116 print!("] → Reconstructed: [");
117 for val in reconstructed.row(i).iter() {
118 print!("{:.0} ", val);
119 }
120 println!("]");
121 }
122
123 Ok(())
124}Sourcepub fn temperature(&self) -> f64
pub fn temperature(&self) -> f64
Get temperature
Examples found in repository?
examples/quantum_boltzmann.rs (line 179)
157fn energy_landscape_demo() -> Result<()> {
158 // Create small QBM for visualization
159 let qbm = QuantumBoltzmannMachine::new(
160 2, // visible units (for 2D visualization)
161 1, // hidden unit
162 0.5, // temperature
163 0.01, // learning rate
164 )?;
165
166 println!(" Analyzing energy landscape of 2-unit system");
167
168 // Compute energy for all 4 possible states
169 let states = vec![
170 Array1::from_vec(vec![0.0, 0.0]),
171 Array1::from_vec(vec![0.0, 1.0]),
172 Array1::from_vec(vec![1.0, 0.0]),
173 Array1::from_vec(vec![1.0, 1.0]),
174 ];
175
176 println!("\n State energies:");
177 for (i, state) in states.iter().enumerate() {
178 let energy = qbm.energy(state);
179 let prob = (-energy / qbm.temperature()).exp();
180 println!(
181 " State [{:.0}, {:.0}]: E = {:.3}, P ∝ {:.3}",
182 state[0], state[1], energy, prob
183 );
184 }
185
186 // Show coupling matrix
187 println!("\n Coupling matrix:");
188 for i in 0..3 {
189 print!(" [");
190 for j in 0..3 {
191 print!("{:6.3} ", qbm.couplings()[[i, j]]);
192 }
193 println!("]");
194 }
195
196 Ok(())
197}Sourcepub fn couplings(&self) -> &Array2<f64>
pub fn couplings(&self) -> &Array2<f64>
Get couplings matrix
Examples found in repository?
examples/quantum_boltzmann.rs (line 191)
157fn energy_landscape_demo() -> Result<()> {
158 // Create small QBM for visualization
159 let qbm = QuantumBoltzmannMachine::new(
160 2, // visible units (for 2D visualization)
161 1, // hidden unit
162 0.5, // temperature
163 0.01, // learning rate
164 )?;
165
166 println!(" Analyzing energy landscape of 2-unit system");
167
168 // Compute energy for all 4 possible states
169 let states = vec![
170 Array1::from_vec(vec![0.0, 0.0]),
171 Array1::from_vec(vec![0.0, 1.0]),
172 Array1::from_vec(vec![1.0, 0.0]),
173 Array1::from_vec(vec![1.0, 1.0]),
174 ];
175
176 println!("\n State energies:");
177 for (i, state) in states.iter().enumerate() {
178 let energy = qbm.energy(state);
179 let prob = (-energy / qbm.temperature()).exp();
180 println!(
181 " State [{:.0}, {:.0}]: E = {:.3}, P ∝ {:.3}",
182 state[0], state[1], energy, prob
183 );
184 }
185
186 // Show coupling matrix
187 println!("\n Coupling matrix:");
188 for i in 0..3 {
189 print!(" [");
190 for j in 0..3 {
191 print!("{:6.3} ", qbm.couplings()[[i, j]]);
192 }
193 println!("]");
194 }
195
196 Ok(())
197}Auto Trait Implementations§
impl Freeze for QuantumBoltzmannMachine
impl RefUnwindSafe for QuantumBoltzmannMachine
impl Send for QuantumBoltzmannMachine
impl Sync for QuantumBoltzmannMachine
impl Unpin for QuantumBoltzmannMachine
impl UnwindSafe for QuantumBoltzmannMachine
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> 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.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.