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

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