quantum_nlp/
quantum_nlp.rs

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