QuantumLanguageModel

Struct QuantumLanguageModel 

Source
pub struct QuantumLanguageModel {
    pub num_qubits: usize,
    pub embedding_strategy: EmbeddingStrategy,
    pub preprocessor: TextPreprocessor,
    pub embedding: WordEmbedding,
    pub qnn: QuantumNeuralNetwork,
    pub task: NLPTaskType,
    pub labels: Vec<String>,
}
Expand description

Quantum language model for NLP tasks

Fields§

§num_qubits: usize

Number of qubits

§embedding_strategy: EmbeddingStrategy

Embedding strategy

§preprocessor: TextPreprocessor

Text preprocessor

§embedding: WordEmbedding

Word embedding

§qnn: QuantumNeuralNetwork

Quantum neural network

§task: NLPTaskType

Type of NLP task

§labels: Vec<String>

Class labels (for classification tasks)

Implementations§

Source§

impl QuantumLanguageModel

Source

pub fn new( num_qubits: usize, embedding_dimension: usize, strategy: EmbeddingStrategy, task: NLPTaskType, labels: Vec<String>, ) -> Result<Self>

Creates a new quantum language model

Examples found in repository?
examples/quantum_nlp.rs (lines 33-44)
23fn run_text_classification() -> Result<()> {
24    println!("\nText Classification Example");
25    println!("--------------------------");
26
27    // Create quantum language model for classification
28    let num_qubits = 6;
29    let embedding_dim = 16;
30    let embedding_strategy = EmbeddingStrategy::from(64); // Was max_seq_length before
31
32    println!("Creating quantum language model with {} qubits", num_qubits);
33    let mut model = QuantumLanguageModel::new(
34        num_qubits,
35        embedding_dim,
36        embedding_strategy,
37        NLPTaskType::Classification,
38        vec![
39            "technology".to_string(),
40            "sports".to_string(),
41            "politics".to_string(),
42            "entertainment".to_string(),
43        ],
44    )?;
45
46    // Create training data
47    println!("Preparing training data...");
48    let training_texts = vec![
49        "Latest smartphone features advanced AI capabilities".to_string(),
50        "The football team won the championship yesterday".to_string(),
51        "New legislation passed regarding climate change".to_string(),
52        "The movie premiere attracted numerous celebrities".to_string(),
53        "Software engineers developed a new programming language".to_string(),
54        "Athletes compete in the international tournament next week".to_string(),
55        "Senator announces campaign for presidential election".to_string(),
56        "Actor receives award for outstanding performance".to_string(),
57    ];
58
59    let training_labels = vec![0, 1, 2, 3, 0, 1, 2, 3];
60
61    // Build vocabulary
62    println!("Building vocabulary from training texts...");
63    let vocab_size = model.build_vocabulary(&training_texts)?;
64    println!("Vocabulary size: {}", vocab_size);
65
66    // Train embeddings
67    println!("Training word embeddings...");
68    model.train_embeddings(&training_texts)?;
69
70    // Train model
71    println!("Training quantum language model...");
72    let start = Instant::now();
73    model.train(&training_texts, &training_labels, 10, 0.05)?;
74    println!("Training completed in {:.2?}", start.elapsed());
75
76    // Test classification
77    let test_texts = [
78        "New computer processor breaks performance records",
79        "Basketball player scores winning point in final seconds",
80        "Government announces new tax policy",
81        "New series premieres with record viewership",
82    ];
83
84    println!("\nClassifying test texts:");
85    for text in &test_texts {
86        let start = Instant::now();
87        let (category, confidence) = model.classify(text)?;
88
89        println!("Text: \"{}\"", text);
90        println!(
91            "Classification: {} (confidence: {:.2})",
92            category, confidence
93        );
94        println!("Classification time: {:.2?}\n", start.elapsed());
95    }
96
97    Ok(())
98}
Source

pub fn fit(&mut self, texts: &[&str], labels: &[usize]) -> Result<()>

Fits the model on a corpus

Source

pub fn predict(&self, text: &str) -> Result<(String, f64)>

Predicts the label for a text

Source§

impl QuantumLanguageModel

Implementation of missing methods for QuantumLanguageModel

Source

pub fn build_vocabulary(&mut self, texts: &[String]) -> Result<usize>

Builds vocabulary from a set of texts

Examples found in repository?
examples/quantum_nlp.rs (line 63)
23fn run_text_classification() -> Result<()> {
24    println!("\nText Classification Example");
25    println!("--------------------------");
26
27    // Create quantum language model for classification
28    let num_qubits = 6;
29    let embedding_dim = 16;
30    let embedding_strategy = EmbeddingStrategy::from(64); // Was max_seq_length before
31
32    println!("Creating quantum language model with {} qubits", num_qubits);
33    let mut model = QuantumLanguageModel::new(
34        num_qubits,
35        embedding_dim,
36        embedding_strategy,
37        NLPTaskType::Classification,
38        vec![
39            "technology".to_string(),
40            "sports".to_string(),
41            "politics".to_string(),
42            "entertainment".to_string(),
43        ],
44    )?;
45
46    // Create training data
47    println!("Preparing training data...");
48    let training_texts = vec![
49        "Latest smartphone features advanced AI capabilities".to_string(),
50        "The football team won the championship yesterday".to_string(),
51        "New legislation passed regarding climate change".to_string(),
52        "The movie premiere attracted numerous celebrities".to_string(),
53        "Software engineers developed a new programming language".to_string(),
54        "Athletes compete in the international tournament next week".to_string(),
55        "Senator announces campaign for presidential election".to_string(),
56        "Actor receives award for outstanding performance".to_string(),
57    ];
58
59    let training_labels = vec![0, 1, 2, 3, 0, 1, 2, 3];
60
61    // Build vocabulary
62    println!("Building vocabulary from training texts...");
63    let vocab_size = model.build_vocabulary(&training_texts)?;
64    println!("Vocabulary size: {}", vocab_size);
65
66    // Train embeddings
67    println!("Training word embeddings...");
68    model.train_embeddings(&training_texts)?;
69
70    // Train model
71    println!("Training quantum language model...");
72    let start = Instant::now();
73    model.train(&training_texts, &training_labels, 10, 0.05)?;
74    println!("Training completed in {:.2?}", start.elapsed());
75
76    // Test classification
77    let test_texts = [
78        "New computer processor breaks performance records",
79        "Basketball player scores winning point in final seconds",
80        "Government announces new tax policy",
81        "New series premieres with record viewership",
82    ];
83
84    println!("\nClassifying test texts:");
85    for text in &test_texts {
86        let start = Instant::now();
87        let (category, confidence) = model.classify(text)?;
88
89        println!("Text: \"{}\"", text);
90        println!(
91            "Classification: {} (confidence: {:.2})",
92            category, confidence
93        );
94        println!("Classification time: {:.2?}\n", start.elapsed());
95    }
96
97    Ok(())
98}
Source

pub fn train_embeddings(&mut self, texts: &[String]) -> Result<()>

Trains word embeddings

Examples found in repository?
examples/quantum_nlp.rs (line 68)
23fn run_text_classification() -> Result<()> {
24    println!("\nText Classification Example");
25    println!("--------------------------");
26
27    // Create quantum language model for classification
28    let num_qubits = 6;
29    let embedding_dim = 16;
30    let embedding_strategy = EmbeddingStrategy::from(64); // Was max_seq_length before
31
32    println!("Creating quantum language model with {} qubits", num_qubits);
33    let mut model = QuantumLanguageModel::new(
34        num_qubits,
35        embedding_dim,
36        embedding_strategy,
37        NLPTaskType::Classification,
38        vec![
39            "technology".to_string(),
40            "sports".to_string(),
41            "politics".to_string(),
42            "entertainment".to_string(),
43        ],
44    )?;
45
46    // Create training data
47    println!("Preparing training data...");
48    let training_texts = vec![
49        "Latest smartphone features advanced AI capabilities".to_string(),
50        "The football team won the championship yesterday".to_string(),
51        "New legislation passed regarding climate change".to_string(),
52        "The movie premiere attracted numerous celebrities".to_string(),
53        "Software engineers developed a new programming language".to_string(),
54        "Athletes compete in the international tournament next week".to_string(),
55        "Senator announces campaign for presidential election".to_string(),
56        "Actor receives award for outstanding performance".to_string(),
57    ];
58
59    let training_labels = vec![0, 1, 2, 3, 0, 1, 2, 3];
60
61    // Build vocabulary
62    println!("Building vocabulary from training texts...");
63    let vocab_size = model.build_vocabulary(&training_texts)?;
64    println!("Vocabulary size: {}", vocab_size);
65
66    // Train embeddings
67    println!("Training word embeddings...");
68    model.train_embeddings(&training_texts)?;
69
70    // Train model
71    println!("Training quantum language model...");
72    let start = Instant::now();
73    model.train(&training_texts, &training_labels, 10, 0.05)?;
74    println!("Training completed in {:.2?}", start.elapsed());
75
76    // Test classification
77    let test_texts = [
78        "New computer processor breaks performance records",
79        "Basketball player scores winning point in final seconds",
80        "Government announces new tax policy",
81        "New series premieres with record viewership",
82    ];
83
84    println!("\nClassifying test texts:");
85    for text in &test_texts {
86        let start = Instant::now();
87        let (category, confidence) = model.classify(text)?;
88
89        println!("Text: \"{}\"", text);
90        println!(
91            "Classification: {} (confidence: {:.2})",
92            category, confidence
93        );
94        println!("Classification time: {:.2?}\n", start.elapsed());
95    }
96
97    Ok(())
98}
Source

pub fn train( &mut self, texts: &[String], labels: &[usize], epochs: usize, learning_rate: f64, ) -> Result<()>

Trains the language model

Examples found in repository?
examples/quantum_nlp.rs (line 73)
23fn run_text_classification() -> Result<()> {
24    println!("\nText Classification Example");
25    println!("--------------------------");
26
27    // Create quantum language model for classification
28    let num_qubits = 6;
29    let embedding_dim = 16;
30    let embedding_strategy = EmbeddingStrategy::from(64); // Was max_seq_length before
31
32    println!("Creating quantum language model with {} qubits", num_qubits);
33    let mut model = QuantumLanguageModel::new(
34        num_qubits,
35        embedding_dim,
36        embedding_strategy,
37        NLPTaskType::Classification,
38        vec![
39            "technology".to_string(),
40            "sports".to_string(),
41            "politics".to_string(),
42            "entertainment".to_string(),
43        ],
44    )?;
45
46    // Create training data
47    println!("Preparing training data...");
48    let training_texts = vec![
49        "Latest smartphone features advanced AI capabilities".to_string(),
50        "The football team won the championship yesterday".to_string(),
51        "New legislation passed regarding climate change".to_string(),
52        "The movie premiere attracted numerous celebrities".to_string(),
53        "Software engineers developed a new programming language".to_string(),
54        "Athletes compete in the international tournament next week".to_string(),
55        "Senator announces campaign for presidential election".to_string(),
56        "Actor receives award for outstanding performance".to_string(),
57    ];
58
59    let training_labels = vec![0, 1, 2, 3, 0, 1, 2, 3];
60
61    // Build vocabulary
62    println!("Building vocabulary from training texts...");
63    let vocab_size = model.build_vocabulary(&training_texts)?;
64    println!("Vocabulary size: {}", vocab_size);
65
66    // Train embeddings
67    println!("Training word embeddings...");
68    model.train_embeddings(&training_texts)?;
69
70    // Train model
71    println!("Training quantum language model...");
72    let start = Instant::now();
73    model.train(&training_texts, &training_labels, 10, 0.05)?;
74    println!("Training completed in {:.2?}", start.elapsed());
75
76    // Test classification
77    let test_texts = [
78        "New computer processor breaks performance records",
79        "Basketball player scores winning point in final seconds",
80        "Government announces new tax policy",
81        "New series premieres with record viewership",
82    ];
83
84    println!("\nClassifying test texts:");
85    for text in &test_texts {
86        let start = Instant::now();
87        let (category, confidence) = model.classify(text)?;
88
89        println!("Text: \"{}\"", text);
90        println!(
91            "Classification: {} (confidence: {:.2})",
92            category, confidence
93        );
94        println!("Classification time: {:.2?}\n", start.elapsed());
95    }
96
97    Ok(())
98}
Source

pub fn classify(&self, text: &str) -> Result<(String, f64)>

Classifies a text

Examples found in repository?
examples/quantum_nlp.rs (line 87)
23fn run_text_classification() -> Result<()> {
24    println!("\nText Classification Example");
25    println!("--------------------------");
26
27    // Create quantum language model for classification
28    let num_qubits = 6;
29    let embedding_dim = 16;
30    let embedding_strategy = EmbeddingStrategy::from(64); // Was max_seq_length before
31
32    println!("Creating quantum language model with {} qubits", num_qubits);
33    let mut model = QuantumLanguageModel::new(
34        num_qubits,
35        embedding_dim,
36        embedding_strategy,
37        NLPTaskType::Classification,
38        vec![
39            "technology".to_string(),
40            "sports".to_string(),
41            "politics".to_string(),
42            "entertainment".to_string(),
43        ],
44    )?;
45
46    // Create training data
47    println!("Preparing training data...");
48    let training_texts = vec![
49        "Latest smartphone features advanced AI capabilities".to_string(),
50        "The football team won the championship yesterday".to_string(),
51        "New legislation passed regarding climate change".to_string(),
52        "The movie premiere attracted numerous celebrities".to_string(),
53        "Software engineers developed a new programming language".to_string(),
54        "Athletes compete in the international tournament next week".to_string(),
55        "Senator announces campaign for presidential election".to_string(),
56        "Actor receives award for outstanding performance".to_string(),
57    ];
58
59    let training_labels = vec![0, 1, 2, 3, 0, 1, 2, 3];
60
61    // Build vocabulary
62    println!("Building vocabulary from training texts...");
63    let vocab_size = model.build_vocabulary(&training_texts)?;
64    println!("Vocabulary size: {}", vocab_size);
65
66    // Train embeddings
67    println!("Training word embeddings...");
68    model.train_embeddings(&training_texts)?;
69
70    // Train model
71    println!("Training quantum language model...");
72    let start = Instant::now();
73    model.train(&training_texts, &training_labels, 10, 0.05)?;
74    println!("Training completed in {:.2?}", start.elapsed());
75
76    // Test classification
77    let test_texts = [
78        "New computer processor breaks performance records",
79        "Basketball player scores winning point in final seconds",
80        "Government announces new tax policy",
81        "New series premieres with record viewership",
82    ];
83
84    println!("\nClassifying test texts:");
85    for text in &test_texts {
86        let start = Instant::now();
87        let (category, confidence) = model.classify(text)?;
88
89        println!("Text: \"{}\"", text);
90        println!(
91            "Classification: {} (confidence: {:.2})",
92            category, confidence
93        );
94        println!("Classification time: {:.2?}\n", start.elapsed());
95    }
96
97    Ok(())
98}

Trait Implementations§

Source§

impl Clone for QuantumLanguageModel

Source§

fn clone(&self) -> QuantumLanguageModel

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for QuantumLanguageModel

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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

Source§

impl<T> Ungil for T
where T: Send,