FewShotLearner

Struct FewShotLearner 

Source
pub struct FewShotLearner { /* private fields */ }
Expand description

Few-shot learning manager

Implementations§

Source§

impl FewShotLearner

Source

pub fn new(method: FewShotMethod, model: QuantumNeuralNetwork) -> Self

Create a new few-shot learner

Examples found in repository?
examples/few_shot_learning.rs (line 90)
85fn test_prototypical_networks(
86    data: &Array2<f64>,
87    labels: &Array1<usize>,
88    qnn: QuantumNeuralNetwork,
89) -> Result<()> {
90    let mut learner = FewShotLearner::new(FewShotMethod::PrototypicalNetworks, qnn);
91
92    // Generate episodes for training
93    let num_episodes = 10;
94    let mut episodes = Vec::new();
95
96    for _ in 0..num_episodes {
97        let episode = FewShotLearner::generate_episode(
98            data, labels, 5, // 5-way
99            3, // 3-shot
100            5, // 5 query examples per class
101        )?;
102        episodes.push(episode);
103    }
104
105    // Train
106    let mut optimizer = Adam::new(0.01);
107    let accuracies = learner.train(&episodes, &mut optimizer, 20)?;
108
109    // Print results
110    println!("   Training completed:");
111    println!("   - Initial accuracy: {:.2}%", accuracies[0] * 100.0);
112    println!(
113        "   - Final accuracy: {:.2}%",
114        accuracies.last().unwrap() * 100.0
115    );
116    println!(
117        "   - Improvement: {:.2}%",
118        (accuracies.last().unwrap() - accuracies[0]) * 100.0
119    );
120
121    Ok(())
122}
123
124/// Test MAML
125fn test_maml(data: &Array2<f64>, labels: &Array1<usize>, qnn: QuantumNeuralNetwork) -> Result<()> {
126    let mut learner = FewShotLearner::new(
127        FewShotMethod::MAML {
128            inner_steps: 5,
129            inner_lr: 0.01,
130        },
131        qnn,
132    );
133
134    // Generate meta-training tasks
135    let num_tasks = 20;
136    let mut tasks = Vec::new();
137
138    for _ in 0..num_tasks {
139        let task = FewShotLearner::generate_episode(
140            data, labels, 3, // 3-way (fewer classes for MAML)
141            5, // 5-shot
142            5, // 5 query examples
143        )?;
144        tasks.push(task);
145    }
146
147    // Meta-train
148    let mut meta_optimizer = Adam::new(0.001);
149    let losses = learner.train(&tasks, &mut meta_optimizer, 10)?;
150
151    println!("   Meta-training completed:");
152    println!("   - Initial loss: {:.4}", losses[0]);
153    println!("   - Final loss: {:.4}", losses.last().unwrap());
154    println!(
155        "   - Convergence rate: {:.2}%",
156        (1.0 - losses.last().unwrap() / losses[0]) * 100.0
157    );
158
159    Ok(())
160}
161
162/// Compare performance across different K-shot values
163fn compare_shot_performance(
164    data: &Array2<f64>,
165    labels: &Array1<usize>,
166    qnn: QuantumNeuralNetwork,
167) -> Result<()> {
168    let k_values = vec![1, 3, 5, 10];
169
170    for k in k_values {
171        println!("\n   Testing {k}-shot learning:");
172
173        let mut learner = FewShotLearner::new(FewShotMethod::PrototypicalNetworks, qnn.clone());
174
175        // Generate episodes
176        let mut episodes = Vec::new();
177        for _ in 0..5 {
178            let episode = FewShotLearner::generate_episode(
179                data, labels, 3, // 3-way
180                k, // k-shot
181                5, // 5 query
182            )?;
183            episodes.push(episode);
184        }
185
186        // Quick training
187        let mut optimizer = Adam::new(0.01);
188        let accuracies = learner.train(&episodes, &mut optimizer, 10)?;
189
190        println!(
191            "     Final accuracy: {:.2}%",
192            accuracies.last().unwrap() * 100.0
193        );
194    }
195
196    Ok(())
197}
Source

pub fn generate_episode( data: &Array2<f64>, labels: &Array1<usize>, num_classes: usize, k_shot: usize, query_per_class: usize, ) -> Result<Episode>

Generate episode from dataset

Examples found in repository?
examples/few_shot_learning.rs (lines 97-101)
85fn test_prototypical_networks(
86    data: &Array2<f64>,
87    labels: &Array1<usize>,
88    qnn: QuantumNeuralNetwork,
89) -> Result<()> {
90    let mut learner = FewShotLearner::new(FewShotMethod::PrototypicalNetworks, qnn);
91
92    // Generate episodes for training
93    let num_episodes = 10;
94    let mut episodes = Vec::new();
95
96    for _ in 0..num_episodes {
97        let episode = FewShotLearner::generate_episode(
98            data, labels, 5, // 5-way
99            3, // 3-shot
100            5, // 5 query examples per class
101        )?;
102        episodes.push(episode);
103    }
104
105    // Train
106    let mut optimizer = Adam::new(0.01);
107    let accuracies = learner.train(&episodes, &mut optimizer, 20)?;
108
109    // Print results
110    println!("   Training completed:");
111    println!("   - Initial accuracy: {:.2}%", accuracies[0] * 100.0);
112    println!(
113        "   - Final accuracy: {:.2}%",
114        accuracies.last().unwrap() * 100.0
115    );
116    println!(
117        "   - Improvement: {:.2}%",
118        (accuracies.last().unwrap() - accuracies[0]) * 100.0
119    );
120
121    Ok(())
122}
123
124/// Test MAML
125fn test_maml(data: &Array2<f64>, labels: &Array1<usize>, qnn: QuantumNeuralNetwork) -> Result<()> {
126    let mut learner = FewShotLearner::new(
127        FewShotMethod::MAML {
128            inner_steps: 5,
129            inner_lr: 0.01,
130        },
131        qnn,
132    );
133
134    // Generate meta-training tasks
135    let num_tasks = 20;
136    let mut tasks = Vec::new();
137
138    for _ in 0..num_tasks {
139        let task = FewShotLearner::generate_episode(
140            data, labels, 3, // 3-way (fewer classes for MAML)
141            5, // 5-shot
142            5, // 5 query examples
143        )?;
144        tasks.push(task);
145    }
146
147    // Meta-train
148    let mut meta_optimizer = Adam::new(0.001);
149    let losses = learner.train(&tasks, &mut meta_optimizer, 10)?;
150
151    println!("   Meta-training completed:");
152    println!("   - Initial loss: {:.4}", losses[0]);
153    println!("   - Final loss: {:.4}", losses.last().unwrap());
154    println!(
155        "   - Convergence rate: {:.2}%",
156        (1.0 - losses.last().unwrap() / losses[0]) * 100.0
157    );
158
159    Ok(())
160}
161
162/// Compare performance across different K-shot values
163fn compare_shot_performance(
164    data: &Array2<f64>,
165    labels: &Array1<usize>,
166    qnn: QuantumNeuralNetwork,
167) -> Result<()> {
168    let k_values = vec![1, 3, 5, 10];
169
170    for k in k_values {
171        println!("\n   Testing {k}-shot learning:");
172
173        let mut learner = FewShotLearner::new(FewShotMethod::PrototypicalNetworks, qnn.clone());
174
175        // Generate episodes
176        let mut episodes = Vec::new();
177        for _ in 0..5 {
178            let episode = FewShotLearner::generate_episode(
179                data, labels, 3, // 3-way
180                k, // k-shot
181                5, // 5 query
182            )?;
183            episodes.push(episode);
184        }
185
186        // Quick training
187        let mut optimizer = Adam::new(0.01);
188        let accuracies = learner.train(&episodes, &mut optimizer, 10)?;
189
190        println!(
191            "     Final accuracy: {:.2}%",
192            accuracies.last().unwrap() * 100.0
193        );
194    }
195
196    Ok(())
197}
Source

pub fn train( &mut self, episodes: &[Episode], optimizer: &mut dyn Optimizer, epochs: usize, ) -> Result<Vec<f64>>

Train the few-shot learner

Examples found in repository?
examples/few_shot_learning.rs (line 107)
85fn test_prototypical_networks(
86    data: &Array2<f64>,
87    labels: &Array1<usize>,
88    qnn: QuantumNeuralNetwork,
89) -> Result<()> {
90    let mut learner = FewShotLearner::new(FewShotMethod::PrototypicalNetworks, qnn);
91
92    // Generate episodes for training
93    let num_episodes = 10;
94    let mut episodes = Vec::new();
95
96    for _ in 0..num_episodes {
97        let episode = FewShotLearner::generate_episode(
98            data, labels, 5, // 5-way
99            3, // 3-shot
100            5, // 5 query examples per class
101        )?;
102        episodes.push(episode);
103    }
104
105    // Train
106    let mut optimizer = Adam::new(0.01);
107    let accuracies = learner.train(&episodes, &mut optimizer, 20)?;
108
109    // Print results
110    println!("   Training completed:");
111    println!("   - Initial accuracy: {:.2}%", accuracies[0] * 100.0);
112    println!(
113        "   - Final accuracy: {:.2}%",
114        accuracies.last().unwrap() * 100.0
115    );
116    println!(
117        "   - Improvement: {:.2}%",
118        (accuracies.last().unwrap() - accuracies[0]) * 100.0
119    );
120
121    Ok(())
122}
123
124/// Test MAML
125fn test_maml(data: &Array2<f64>, labels: &Array1<usize>, qnn: QuantumNeuralNetwork) -> Result<()> {
126    let mut learner = FewShotLearner::new(
127        FewShotMethod::MAML {
128            inner_steps: 5,
129            inner_lr: 0.01,
130        },
131        qnn,
132    );
133
134    // Generate meta-training tasks
135    let num_tasks = 20;
136    let mut tasks = Vec::new();
137
138    for _ in 0..num_tasks {
139        let task = FewShotLearner::generate_episode(
140            data, labels, 3, // 3-way (fewer classes for MAML)
141            5, // 5-shot
142            5, // 5 query examples
143        )?;
144        tasks.push(task);
145    }
146
147    // Meta-train
148    let mut meta_optimizer = Adam::new(0.001);
149    let losses = learner.train(&tasks, &mut meta_optimizer, 10)?;
150
151    println!("   Meta-training completed:");
152    println!("   - Initial loss: {:.4}", losses[0]);
153    println!("   - Final loss: {:.4}", losses.last().unwrap());
154    println!(
155        "   - Convergence rate: {:.2}%",
156        (1.0 - losses.last().unwrap() / losses[0]) * 100.0
157    );
158
159    Ok(())
160}
161
162/// Compare performance across different K-shot values
163fn compare_shot_performance(
164    data: &Array2<f64>,
165    labels: &Array1<usize>,
166    qnn: QuantumNeuralNetwork,
167) -> Result<()> {
168    let k_values = vec![1, 3, 5, 10];
169
170    for k in k_values {
171        println!("\n   Testing {k}-shot learning:");
172
173        let mut learner = FewShotLearner::new(FewShotMethod::PrototypicalNetworks, qnn.clone());
174
175        // Generate episodes
176        let mut episodes = Vec::new();
177        for _ in 0..5 {
178            let episode = FewShotLearner::generate_episode(
179                data, labels, 3, // 3-way
180                k, // k-shot
181                5, // 5 query
182            )?;
183            episodes.push(episode);
184        }
185
186        // Quick training
187        let mut optimizer = Adam::new(0.01);
188        let accuracies = learner.train(&episodes, &mut optimizer, 10)?;
189
190        println!(
191            "     Final accuracy: {:.2}%",
192            accuracies.last().unwrap() * 100.0
193        );
194    }
195
196    Ok(())
197}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

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 more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

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

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V