### Example output from training and running the classifier Source: https://github.com/thomasdidion/bayespam/blob/main/README.md This output shows the results after training a custom classifier and then running it on sample messages, indicating the probability score and spam identification. ```bash $> cargo run 0.9999 true 0.0001 false ``` -------------------------------- ### Example output from running the classifier Source: https://github.com/thomasdidion/bayespam/blob/main/README.md This output demonstrates the results of running the spam classifier on sample messages, showing the probability score and whether the message is identified as spam. ```bash $> cargo run 0.9993 true 0.6311 false ``` -------------------------------- ### Create a New Classifier Source: https://context7.com/thomasdidion/bayespam/llms.txt Initializes a new, empty classifier ready for training with spam and ham examples. ```rust use bayespam::classifier::Classifier; fn main() { // Create a new classifier with an empty model let mut classifier = Classifier::new(); // The classifier is ready for training println!("Classifier created successfully"); } ``` -------------------------------- ### Example of a saved spam classifier model Source: https://github.com/thomasdidion/bayespam/blob/main/README.md This is an example of the JSON output generated when saving a trained spam classifier model. It contains token frequencies for ham and spam categories. ```json {"token_table":{"forget":{"ham":1,"spam":1},"only":{"ham":0,"spam":1},"meeting":{"ham":1,"spam":0},"our":{"ham":1,"spam":1},"dont":{"ham":1,"spam":1},"bob":{"ham":1,"spam":0},"men":{"ham":0,"spam":1},"today":{"ham":1,"spam":1},"shoes":{"ham":0,"spam":1},"special":{"ham":0,"spam":1},"promotion:":{"ham":0,"spam":1}}} ``` -------------------------------- ### Classifier::new Source: https://context7.com/thomasdidion/bayespam/llms.txt Creates a new classifier with an empty model, ready for training with spam and ham examples. ```APIDOC ## Classifier::new ### Description Creates a new classifier with an empty model, ready for training with spam and ham examples. ### Method Associated function (constructor-like) ### Endpoint N/A (Instance method) ### Parameters None ### Request Example ```rust use bayespam::classifier::Classifier; fn main() { let mut classifier = Classifier::new(); println!("Classifier created successfully"); } ``` ### Response N/A (Returns a new Classifier instance) ``` -------------------------------- ### Train and save a custom spam classifier model Source: https://github.com/thomasdidion/bayespam/blob/main/README.md Train a new classifier from scratch with custom spam and ham examples, then save the model to a JSON file. This allows for later reloading and reuse. ```rust use bayespam::classifier::Classifier; use std::fs::File; fn main() -> Result<(), std::io::Error> { // Create a new classifier with an empty model let mut classifier = Classifier::new(); // Train the classifier with a new spam example let spam = "Don't forget our special promotion: -30% on men shoes, only today!"; classifier.train_spam(spam); // Train the classifier with a new ham example let ham = "Hi Bob, don't forget our meeting today at 4pm."; classifier.train_ham(ham); // Identify a typical spam message let spam = "Lose up to 19% weight. Special promotion on our new weightloss."; let score = classifier.score(spam); let is_spam = classifier.identify(spam); println!(/*{:.4}*/ "{:.4}", score); println!(/*{}*/ "{}", is_spam); // Identify a typical ham message let ham = "Hi Bob, can you send me your machine learning homework?"; let score = classifier.score(ham); let is_spam = classifier.identify(ham); println!(/*{:.4}*/ "{:.4}", score); println!(/*{}*/ "{}", is_spam); // Serialize the model and save it as JSON into a file let mut file = File::create("my_super_model.json")?; classifier.save(&mut file, false)?; Ok(()) } ``` -------------------------------- ### Train and Score Messages with Classifier Source: https://context7.com/thomasdidion/bayespam/llms.txt Trains a classifier with spam and ham examples, then scores various messages to determine their spam probability. Output scores range from 0.0 (ham) to 1.0 (spam). ```rust use bayespam::classifier::Classifier; fn main() { let mut classifier = Classifier::new(); // Train the classifier classifier.train_spam("Buy now! Special discount just for you!"); classifier.train_spam("Free gift! Limited time offer!"); classifier.train_ham("Meeting scheduled for tomorrow at 3pm."); classifier.train_ham("Please review the attached document."); // Score various messages let spam_message = "Exclusive discount! Buy now and save big!"; let spam_score = classifier.score(spam_message); println!("Spam message score: {:.4}", spam_score); // Output: Spam message score: 0.9999 let ham_message = "Can we reschedule the meeting to next week?"; let ham_score = classifier.score(ham_message); println!("Ham message score: {:.4}", ham_score); // Output: Ham message score: 0.0001 let ambiguous = "Please review this special offer document."; let ambiguous_score = classifier.score(ambiguous); println!("Ambiguous message score: {:.4}", ambiguous_score); // Output varies based on training data } ``` -------------------------------- ### Train, Test, and Persist Classifier Source: https://context7.com/thomasdidion/bayespam/llms.txt Demonstrates the full lifecycle of creating a classifier, training it on datasets, testing accuracy, and saving/loading the model to a file. ```rust use bayespam::classifier::Classifier; use std::fs::File; fn main() -> Result<(), std::io::Error> { // Phase 1: Create and train a new classifier let mut classifier = Classifier::new(); // Training data - spam examples let spam_samples = vec![ "Don't forget our special promotion: -30% on men shoes, only today!", "Congratulations! You've won $1,000,000! Click to claim!", "URGENT: Your bank account needs verification immediately!", "Free weight loss pills! Lose 30 pounds in 30 days!", "Hot singles in your area want to meet you tonight!", ]; // Training data - ham examples let ham_samples = vec![ "Hi Bob, don't forget our meeting today at 4pm.", "Please review the attached quarterly report.", "Can you send me the project timeline?", "Thanks for your help with the presentation.", "Let's grab lunch tomorrow if you're free.", ]; // Train the classifier for spam in &spam_samples { classifier.train_spam(spam); } for ham in &ham_samples { classifier.train_ham(ham); } // Phase 2: Test the trained classifier let test_messages = vec![ ("Win a free cruise! Limited spots available!", true), ("Meeting rescheduled to 3pm tomorrow", false), ("Your account will be suspended! Verify now!", true), ("Here are the files you requested", false), ]; println!("Testing classifier accuracy:"); for (msg, expected_spam) in &test_messages { let score = classifier.score(msg); let is_spam = classifier.identify(msg); let status = if *expected_spam == is_spam { "CORRECT" } else { "WRONG" }; println!(" [{}] Score: {:.4}, Spam: {} - '{}'", status, score, is_spam, msg); } // Phase 3: Save the trained model let mut file = File::create("my_trained_model.json")?; classifier.save(&mut file, false)?; println!("\nModel saved to my_trained_model.json"); // Phase 4: Load and use the saved model let mut file = File::open("my_trained_model.json")?; let loaded_classifier = Classifier::new_from_pre_trained(&mut file)?; let new_message = "Special offer just for you! 50% discount!"; let is_spam = loaded_classifier.identify(new_message); println!("\nLoaded model test: '{}' is spam: {}", new_message, is_spam); Ok(()) } // Output: // Testing classifier accuracy: // [CORRECT] Score: 0.9999, Spam: true - 'Win a free cruise! Limited spots available!' // [CORRECT] Score: 0.0001, Spam: false - 'Meeting rescheduled to 3pm tomorrow' // [CORRECT] Score: 0.9999, Spam: true - 'Your account will be suspended! Verify now!' // [CORRECT] Score: 0.0001, Spam: false - 'Here are the files you requested' // // Model saved to my_trained_model.json // // Loaded model test: 'Special offer just for you! 50% discount!' is spam: true ``` -------------------------------- ### Add bayespam to Cargo.toml Source: https://github.com/thomasdidion/bayespam/blob/main/README.md To use the bayespam crate, add it as a dependency in your Cargo.toml file. ```toml [dependencies] bayespam = "1.2.0" ``` -------------------------------- ### Classifier::new_from_pre_trained Source: https://context7.com/thomasdidion/bayespam/llms.txt Loads a classifier from a pre-trained JSON model file, enabling immediate spam detection without additional training. ```APIDOC ## Classifier::new_from_pre_trained ### Description Loads a classifier from a pre-trained JSON model file, enabling immediate spam detection without additional training. ### Method Associated function (constructor-like) ### Endpoint N/A (Instance method) ### Parameters #### Path Parameters - **file** (std::fs::File) - Required - A mutable reference to a file object containing the pre-trained model in JSON format. ### Request Example ```rust use bayespam::classifier::Classifier; use std::fs::File; fn main() -> Result<(), std::io::Error> { let mut file = File::open("model.json")?; let classifier = Classifier::new_from_pre_trained(&mut file)?; let message = "Special offer! Buy now and save 50%!"; let is_spam = classifier.identify(message); println!("Is spam: {}", is_spam); // Output: Is spam: true Ok(()) } ``` ### Response #### Success Response (200) - **Classifier** (bayespam::classifier::Classifier) - An initialized classifier instance loaded from the provided model file. #### Response Example N/A (Returns a Classifier instance directly) ``` -------------------------------- ### Identify Spam with Pre-trained Model Source: https://context7.com/thomasdidion/bayespam/llms.txt Uses the convenience function to classify text based on a model.json file located in the package root. ```rust use bayespam::classifier; fn main() -> Result<(), std::io::Error> { // Requires model.json in the package root directory // Identify a spam message let spam = "Lose up to 19% weight. Special promotion on our new weightloss."; let is_spam = classifier::identify(spam)?; assert!(is_spam); println!("'{}...' is spam: {}", &spam[..30], is_spam); // Output: 'Lose up to 19% weight. Specia...' is spam: true // Identify a ham message let ham = "Hi Bob, can you send me your machine learning homework?"; let is_spam = classifier::identify(ham)?; assert!(!is_spam); println!("'{}...' is spam: {}", &ham[..30], is_spam); // Output: 'Hi Bob, can you send me your m...' is spam: false Ok(()) } ``` -------------------------------- ### Identify messages using a pre-trained model Source: https://github.com/thomasdidion/bayespam/blob/main/README.md Use a pre-trained model to score and identify messages as spam or ham. Ensure a 'model.json' file is present in the package root. ```rust use bayespam::classifier; fn main() -> Result<(), std::io::Error> { // Identify a typical spam message let spam = "Lose up to 19% weight. Special promotion on our new weightloss."; let score = classifier::score(spam)?; let is_spam = classifier::identify(spam)?; println!(/*{:.4?}*/ "{:.4?}", score); println!(/*{:?}*/ "{:?}", is_spam); // Identify a typical ham message let ham = "Hi Bob, can you send me your machine learning homework?"; let score = classifier::score(ham)?; let is_spam = classifier::identify(ham)?; println!(/*{:.4?}*/ "{:.4?}", score); println!(/*{:?}*/ "{:?}", is_spam); Ok(()) } ``` -------------------------------- ### Load Classifier from Pre-trained Model Source: https://context7.com/thomasdidion/bayespam/llms.txt Loads a classifier from a JSON model file for immediate use. Requires a valid JSON model file. ```rust use bayespam::classifier::Classifier; use std::fs::File; fn main() -> Result<(), std::io::Error> { // Open the pre-trained model file let mut file = File::open("model.json")?; // Load the classifier from the pre-trained model let classifier = Classifier::new_from_pre_trained(&mut file)?; // Use the classifier to identify messages let message = "Special offer! Buy now and save 50%!"; let is_spam = classifier.identify(message); println!("Is spam: {}", is_spam); // Output: Is spam: true Ok(()) } ``` -------------------------------- ### Load and Score Message with Module Function Source: https://context7.com/thomasdidion/bayespam/llms.txt A convenience function that loads a pre-trained model from `model.json` and computes the spam score for a given message. Requires `model.json` in the package root. ```rust use bayespam::classifier; fn main() -> Result<(), std::io::Error> { // Requires model.json in the package root directory // Score a spam message let spam = "Lose up to 19% weight. Special promotion on our new weightloss."; let score = classifier::score(spam)?; println!("Spam score: {:.4}", score); // Output: Spam score: 0.9993 // Score a ham message let ham = "Hi Bob, can you send me your machine learning homework?"; let score = classifier::score(ham)?; println!("Ham score: {:.4}", score); // Output: Ham score: 0.6311 Ok(()) } ``` -------------------------------- ### Train Classifier with Ham (Non-Spam) Messages Source: https://context7.com/thomasdidion/bayespam/llms.txt Trains the classifier with ham messages. Each word is tokenized and its ham count is updated, helping to distinguish legitimate messages. ```rust use bayespam::classifier::Classifier; fn main() { let mut classifier = Classifier::new(); // Train with spam examples classifier.train_spam("Special promotion: -50% off everything!"); classifier.train_spam("You won a prize! Claim now!"); // Train with ham examples classifier.train_ham("Hi Bob, don't forget our meeting today at 4pm."); classifier.train_ham("Can you send me the project files when you have a chance?"); classifier.train_ham("Thanks for your help with the presentation yesterday."); classifier.train_ham("Let's schedule a call to discuss the quarterly results."); // The classifier can now distinguish between spam and legitimate emails let test_ham = "Hi Bob, can you send me your machine learning homework?"; let is_spam = classifier.identify(test_ham); println!("Detected as spam: {}", is_spam); // Output: Detected as spam: false } ``` -------------------------------- ### Save Trained Classifier Model Source: https://context7.com/thomasdidion/bayespam/llms.txt Serializes the trained classifier model to a JSON file. The `pretty` parameter controls output formatting for readability, useful for debugging. ```rust use bayespam::classifier::Classifier; use std::fs::File; fn main() -> Result<(), std::io::Error> { let mut classifier = Classifier::new(); // Train the classifier with examples classifier.train_spam("Special promotion: -30% on all items!"); classifier.train_spam("You've won! Claim your prize now!"); classifier.train_ham("Hi Bob, don't forget our meeting today."); classifier.train_ham("Please send the report when ready."); // Save as compact JSON let mut file = File::create("model_compact.json")?; classifier.save(&mut file, false)?; println!("Compact model saved to model_compact.json"); // Save as pretty-printed JSON for debugging let mut file = File::create("model_pretty.json")?; classifier.save(&mut file, true)?; println!("Pretty model saved to model_pretty.json"); Ok(()) } // model_compact.json contents: // {"token_table":{"promotion":{"ham":0,"spam":1},"meeting":{"ham":1,"spam":0},...}} // model_pretty.json contents: // { // "token_table": { // "promotion": { // "ham": 0, // "spam": 1 // }, // ... // } // } ``` -------------------------------- ### Train Classifier with Spam Messages Source: https://context7.com/thomasdidion/bayespam/llms.txt Trains the classifier by adding spam messages to its model. Each word is tokenized and its spam count is updated. ```rust use bayespam::classifier::Classifier; fn main() { let mut classifier = Classifier::new(); // Train with multiple spam examples classifier.train_spam("Don't forget our special promotion: -30% on men shoes, only today!"); classifier.train_spam("Congratulations! You've won a free vacation. Click here now!"); classifier.train_spam("Limited time offer: Buy one get one free on all products!"); classifier.train_spam("URGENT: Your account needs verification. Send your password immediately."); // The classifier now recognizes common spam patterns let test_spam = "Special promotion just for you! Click now!"; let is_spam = classifier.identify(test_spam); println!("Detected as spam: {}", is_spam); // Output: Detected as spam: true } ``` -------------------------------- ### Identify Spam Messages with Classifier Source: https://context7.com/thomasdidion/bayespam/llms.txt Trains a classifier and then identifies whether messages are spam (score > 0.8) or ham. This method is useful for direct classification of incoming messages. ```rust use bayespam::classifier::Classifier; fn main() { let mut classifier = Classifier::new(); // Train with examples classifier.train_spam("Lose up to 19% weight. Special promotion on our new weightloss."); classifier.train_spam("Congratulations! You've been selected for a cash prize!"); classifier.train_ham("Hi team, here are the meeting notes from today."); classifier.train_ham("The project deadline has been extended to Friday."); // Identify messages let messages = vec![ "Win a free iPhone! Click here immediately!", "Reminder: Team lunch tomorrow at noon", "URGENT: Verify your account or lose access!", "Thanks for the feedback on my draft", ]; for msg in messages { let is_spam = classifier.identify(msg); let label = if is_spam { "SPAM" } else { "HAM" }; println!("[{}] {}", label, msg); } // Output: // [SPAM] Win a free iPhone! Click here immediately! // [HAM] Reminder: Team lunch tomorrow at noon // [SPAM] URGENT: Verify your account or lose access! // [HAM] Thanks for the feedback on my draft } ``` -------------------------------- ### Classifier::save Source: https://context7.com/thomasdidion/bayespam/llms.txt Serializes the trained classifier model to a JSON file for persistence. ```APIDOC ## Classifier::save ### Description Serializes the trained classifier model to a JSON file for persistence. ### Parameters #### Request Body - **file** (File) - Required - The file handle to write the model to. - **pretty** (boolean) - Required - Controls whether the output is formatted for readability. ``` -------------------------------- ### classifier::score (Module Function) Source: https://context7.com/thomasdidion/bayespam/llms.txt Convenience function that loads a pre-trained model from model.json and computes the spam score. ```APIDOC ## classifier::score ### Description Convenience function that loads a pre-trained model from `model.json` in the package root and computes the spam score for a message. ### Parameters #### Request Body - **message** (string) - Required - The text content to be scored. ``` -------------------------------- ### Classifier::train_ham Source: https://context7.com/thomasdidion/bayespam/llms.txt Trains the classifier by adding a ham (non-spam) message to the model. Each word in the message is tokenized and its ham count is incremented in the token table. ```APIDOC ## Classifier::train_ham ### Description Trains the classifier by adding a ham (non-spam) message to the model. Each word in the message is tokenized and its ham count is incremented in the token table. ### Method Instance method ### Endpoint N/A (Instance method) ### Parameters #### Request Body - **message** (string) - Required - The ham message to train the classifier with. ### Request Example ```rust use bayespam::classifier::Classifier; fn main() { let mut classifier = Classifier::new(); classifier.train_spam("Special promotion: -50% off everything!"); classifier.train_spam("You won a prize! Claim now!"); classifier.train_ham("Hi Bob, don't forget our meeting today at 4pm."); classifier.train_ham("Can you send me the project files when you have a chance?"); classifier.train_ham("Thanks for your help with the presentation yesterday."); classifier.train_ham("Let's schedule a call to discuss the quarterly results."); let test_ham = "Hi Bob, can you send me your machine learning homework?"; let is_spam = classifier.identify(test_ham); println!("Detected as spam: {}", is_spam); // Output: Detected as spam: false } ``` ### Response N/A (Modifies the classifier in place) ``` -------------------------------- ### Classifier::train_spam Source: https://context7.com/thomasdidion/bayespam/llms.txt Trains the classifier by adding a spam message to the model. Each word in the message is tokenized and its spam count is incremented in the token table. ```APIDOC ## Classifier::train_spam ### Description Trains the classifier by adding a spam message to the model. Each word in the message is tokenized and its spam count is incremented in the token table. ### Method Instance method ### Endpoint N/A (Instance method) ### Parameters #### Request Body - **message** (string) - Required - The spam message to train the classifier with. ### Request Example ```rust use bayespam::classifier::Classifier; fn main() { let mut classifier = Classifier::new(); classifier.train_spam("Don't forget our special promotion: -30% on men shoes, only today!"); classifier.train_spam("Congratulations! You've won a free vacation. Click here now!"); classifier.train_spam("Limited time offer: Buy one get one free on all products!"); classifier.train_spam("URGENT: Your account needs verification. Send your password immediately."); let test_spam = "Special promotion just for you! Click now!"; let is_spam = classifier.identify(test_spam); println!("Detected as spam: {}", is_spam); // Output: Detected as spam: true } ``` ### Response N/A (Modifies the classifier in place) ``` -------------------------------- ### Classifier::score Source: https://context7.com/thomasdidion/bayespam/llms.txt Computes a spam probability score for a message, returning a value between 0.0 and 1.0. ```APIDOC ## Classifier::score ### Description Computes a spam probability score for a message, returning a value between 0.0 and 1.0. Higher scores indicate a stronger likelihood that the message is spam. ### Parameters #### Request Body - **message** (string) - Required - The text content to be scored. ``` -------------------------------- ### Classifier::identify Source: https://context7.com/thomasdidion/bayespam/llms.txt Identifies whether a message is spam by checking if its score exceeds the 0.8 probability threshold. ```APIDOC ## Classifier::identify ### Description Identifies whether a message is spam by checking if its score exceeds the 0.8 probability threshold. Returns true for spam, false for ham. ### Parameters #### Request Body - **message** (string) - Required - The text content to evaluate. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.