quantum_nlp/
quantum_nlp.rs1use quantrs2_ml::nlp::{
2 EmbeddingStrategy, NLPTaskType, QuantumLanguageModel, TextPreprocessor, WordEmbedding,
3};
4use quantrs2_ml::prelude::*;
5use std::time::Instant;
6
7fn main() -> Result<()> {
8 println!("Quantum Natural Language Processing Examples");
9 println!("==========================================");
10
11 run_text_classification()?;
13
14 run_sentiment_analysis()?;
16
17 run_text_summarization()?;
19
20 Ok(())
21}
22
23fn run_text_classification() -> Result<()> {
24 println!("\nText Classification Example");
25 println!("--------------------------");
26
27 let num_qubits = 6;
29 let embedding_dim = 16;
30 let embedding_strategy = EmbeddingStrategy::from(64); 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 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 println!("Building vocabulary from training texts...");
63 let vocab_size = model.build_vocabulary(&training_texts)?;
64 println!("Vocabulary size: {}", vocab_size);
65
66 println!("Training word embeddings...");
68 model.train_embeddings(&training_texts)?;
69
70 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 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}
99
100fn run_sentiment_analysis() -> Result<()> {
101 println!("\nSentiment Analysis Example");
102 println!("-------------------------");
103
104 let num_qubits = 6;
106 println!(
107 "Creating quantum sentiment analyzer with {} qubits",
108 num_qubits
109 );
110 let analyzer = quantrs2_ml::nlp::SentimentAnalyzer::new(num_qubits)?;
111
112 let test_texts = [
114 "I really enjoyed this product, it works perfectly!",
115 "The service was terrible and the staff was rude",
116 "The movie was okay, nothing special but not bad either",
117 "The experience exceeded all my expectations!",
118 ];
119
120 println!("\nAnalyzing sentiment of test texts:");
121 for text in &test_texts {
122 let start = Instant::now();
123 let (sentiment, confidence) = analyzer.analyze(text)?;
124
125 println!("Text: \"{}\"", text);
126 println!("Sentiment: {} (confidence: {:.2})", sentiment, confidence);
127 println!("Analysis time: {:.2?}\n", start.elapsed());
128 }
129
130 Ok(())
131}
132
133fn run_text_summarization() -> Result<()> {
134 println!("\nText Summarization Example");
135 println!("-------------------------");
136
137 let num_qubits = 8;
139 println!(
140 "Creating quantum text summarizer with {} qubits",
141 num_qubits
142 );
143 let summarizer = quantrs2_ml::nlp::TextSummarizer::new(num_qubits)?;
144
145 let long_text = "Quantum computing is a rapidly-emerging technology that harnesses the laws of quantum mechanics to solve problems too complex for classical computers. While traditional computers use bits as the smallest unit of data, quantum computers use quantum bits or qubits. Qubits can represent numerous possible combinations of 1 and 0 at the same time through a property called superposition. This allows quantum computers to consider and manipulate many combinations of information simultaneously, making them well suited to specific types of complex calculations. Another key property of quantum computing is entanglement, which allows qubits that are separated by great distances to still be connected. Changing the state of one entangled qubit will instantaneously change the state of its partner regardless of how far apart they are. Quantum computers excel at solving certain types of problems, such as factoring very large numbers, searching unsorted databases, and simulating quantum systems like molecules for drug development. However, they are not expected to replace classical computers for most everyday tasks. Major technology companies including IBM, Google, Microsoft, Amazon, and several startups are racing to build practical quantum computers. In 2019, Google claimed to have achieved quantum supremacy, performing a calculation that would be practically impossible for a classical computer. While current quantum computers are still limited by high error rates and the need for extreme cooling, they represent one of the most promising frontier technologies of the 21st century.";
147
148 println!("\nOriginal text ({} characters):", long_text.len());
149 println!("{}\n", long_text);
150
151 println!("Generating quantum summary...");
153 let start = Instant::now();
154 let summary = summarizer.summarize(long_text)?;
155 println!("Summarization completed in {:.2?}", start.elapsed());
156
157 println!("\nSummary ({} characters):", summary.len());
158 println!("{}", summary);
159
160 let compression = 100.0 * (1.0 - (summary.len() as f64) / (long_text.len() as f64));
162 println!("\nCompression ratio: {:.1}%", compression);
163
164 Ok(())
165}