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

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