quantum_nlp/
quantum_nlp.rs1#![allow(clippy::pedantic, clippy::unnecessary_wraps)]
2use quantrs2_ml::nlp::{
3 EmbeddingStrategy, NLPTaskType, QuantumLanguageModel, TextPreprocessor, WordEmbedding,
4};
5use quantrs2_ml::prelude::*;
6use std::time::Instant;
7
8fn main() -> Result<()> {
9 println!("Quantum Natural Language Processing Examples");
10 println!("==========================================");
11
12 run_text_classification()?;
14
15 run_sentiment_analysis()?;
17
18 run_text_summarization()?;
20
21 Ok(())
22}
23
24fn run_text_classification() -> Result<()> {
25 println!("\nText Classification Example");
26 println!("--------------------------");
27
28 let num_qubits = 6;
30 let embedding_dim = 16;
31 let embedding_strategy = EmbeddingStrategy::from(64); println!("Creating quantum language model with {num_qubits} qubits");
34 let mut model = QuantumLanguageModel::new(
35 num_qubits,
36 embedding_dim,
37 embedding_strategy,
38 NLPTaskType::Classification,
39 vec![
40 "technology".to_string(),
41 "sports".to_string(),
42 "politics".to_string(),
43 "entertainment".to_string(),
44 ],
45 )?;
46
47 println!("Preparing training data...");
49 let training_texts = vec![
50 "Latest smartphone features advanced AI capabilities".to_string(),
51 "The football team won the championship yesterday".to_string(),
52 "New legislation passed regarding climate change".to_string(),
53 "The movie premiere attracted numerous celebrities".to_string(),
54 "Software engineers developed a new programming language".to_string(),
55 "Athletes compete in the international tournament next week".to_string(),
56 "Senator announces campaign for presidential election".to_string(),
57 "Actor receives award for outstanding performance".to_string(),
58 ];
59
60 let training_labels = vec![0, 1, 2, 3, 0, 1, 2, 3];
61
62 println!("Building vocabulary from training texts...");
64 let vocab_size = model.build_vocabulary(&training_texts)?;
65 println!("Vocabulary size: {vocab_size}");
66
67 println!("Training word embeddings...");
69 model.train_embeddings(&training_texts)?;
70
71 println!("Training quantum language model...");
73 let start = Instant::now();
74 model.train(&training_texts, &training_labels, 10, 0.05)?;
75 println!("Training completed in {:.2?}", start.elapsed());
76
77 let test_texts = [
79 "New computer processor breaks performance records",
80 "Basketball player scores winning point in final seconds",
81 "Government announces new tax policy",
82 "New series premieres with record viewership",
83 ];
84
85 println!("\nClassifying test texts:");
86 for text in &test_texts {
87 let start = Instant::now();
88 let (category, confidence) = model.classify(text)?;
89
90 println!("Text: \"{text}\"");
91 println!("Classification: {category} (confidence: {confidence:.2})");
92 println!("Classification time: {:.2?}\n", start.elapsed());
93 }
94
95 Ok(())
96}
97
98fn run_sentiment_analysis() -> Result<()> {
99 println!("\nSentiment Analysis Example");
100 println!("-------------------------");
101
102 let num_qubits = 6;
104 println!("Creating quantum sentiment analyzer with {num_qubits} qubits");
105 let analyzer = quantrs2_ml::nlp::SentimentAnalyzer::new(num_qubits)?;
106
107 let test_texts = [
109 "I really enjoyed this product, it works perfectly!",
110 "The service was terrible and the staff was rude",
111 "The movie was okay, nothing special but not bad either",
112 "The experience exceeded all my expectations!",
113 ];
114
115 println!("\nAnalyzing sentiment of test texts:");
116 for text in &test_texts {
117 let start = Instant::now();
118 let (sentiment, confidence) = analyzer.analyze(text)?;
119
120 println!("Text: \"{text}\"");
121 println!("Sentiment: {sentiment} (confidence: {confidence:.2})");
122 println!("Analysis time: {:.2?}\n", start.elapsed());
123 }
124
125 Ok(())
126}
127
128fn run_text_summarization() -> Result<()> {
129 println!("\nText Summarization Example");
130 println!("-------------------------");
131
132 let num_qubits = 8;
134 println!("Creating quantum text summarizer with {num_qubits} qubits");
135 let summarizer = quantrs2_ml::nlp::TextSummarizer::new(num_qubits)?;
136
137 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.";
139
140 println!("\nOriginal text ({} characters):", long_text.len());
141 println!("{long_text}\n");
142
143 println!("Generating quantum summary...");
145 let start = Instant::now();
146 let summary = summarizer.summarize(long_text)?;
147 println!("Summarization completed in {:.2?}", start.elapsed());
148
149 println!("\nSummary ({} characters):", summary.len());
150 println!("{summary}");
151
152 let compression = 100.0 * (1.0 - (summary.len() as f64) / (long_text.len() as f64));
154 println!("\nCompression ratio: {compression:.1}%");
155
156 Ok(())
157}