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 {num_qubits} 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!("Classification: {category} (confidence: {confidence:.2})");
91 println!("Classification time: {:.2?}\n", start.elapsed());
92 }
93
94 Ok(())
95}
96
97fn run_sentiment_analysis() -> Result<()> {
98 println!("\nSentiment Analysis Example");
99 println!("-------------------------");
100
101 let num_qubits = 6;
103 println!("Creating quantum sentiment analyzer with {num_qubits} qubits");
104 let analyzer = quantrs2_ml::nlp::SentimentAnalyzer::new(num_qubits)?;
105
106 let test_texts = [
108 "I really enjoyed this product, it works perfectly!",
109 "The service was terrible and the staff was rude",
110 "The movie was okay, nothing special but not bad either",
111 "The experience exceeded all my expectations!",
112 ];
113
114 println!("\nAnalyzing sentiment of test texts:");
115 for text in &test_texts {
116 let start = Instant::now();
117 let (sentiment, confidence) = analyzer.analyze(text)?;
118
119 println!("Text: \"{text}\"");
120 println!("Sentiment: {sentiment} (confidence: {confidence:.2})");
121 println!("Analysis time: {:.2?}\n", start.elapsed());
122 }
123
124 Ok(())
125}
126
127fn run_text_summarization() -> Result<()> {
128 println!("\nText Summarization Example");
129 println!("-------------------------");
130
131 let num_qubits = 8;
133 println!("Creating quantum text summarizer with {num_qubits} qubits");
134 let summarizer = quantrs2_ml::nlp::TextSummarizer::new(num_qubits)?;
135
136 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.";
138
139 println!("\nOriginal text ({} characters):", long_text.len());
140 println!("{long_text}\n");
141
142 println!("Generating quantum summary...");
144 let start = Instant::now();
145 let summary = summarizer.summarize(long_text)?;
146 println!("Summarization completed in {:.2?}", start.elapsed());
147
148 println!("\nSummary ({} characters):", summary.len());
149 println!("{summary}");
150
151 let compression = 100.0 * (1.0 - (summary.len() as f64) / (long_text.len() as f64));
153 println!("\nCompression ratio: {compression:.1}%");
154
155 Ok(())
156}