### Run CatBoost Rust Examples Source: https://github.com/aryehlev/catboost-rust/blob/publish/README.md Commands to execute the basic and advanced usage examples provided in the crate's `examples/` directory. These examples showcase different functionalities of the CatBoost Rust library. ```bash cargo run --example basic_usage ``` ```bash cargo run --example advanced_usage ``` -------------------------------- ### Install CatBoost and Create Sample Models Source: https://github.com/aryehlev/catboost-rust/blob/publish/examples/README.md Installs the necessary Python packages and generates sample CatBoost models for regression and classification. ```bash pip install catboost numpy pandas python examples/create_sample_model.py ``` -------------------------------- ### Run Basic Usage Example Source: https://github.com/aryehlev/catboost-rust/blob/publish/examples/README.md Executes the basic CatBoost Rust example to demonstrate model loading and prediction with numeric and categorical features. ```bash cargo run --example basic_usage ``` -------------------------------- ### Run Advanced Usage Example Source: https://github.com/aryehlev/catboost-rust/blob/publish/examples/README.md Executes the advanced CatBoost Rust example, showcasing detailed model information, various feature inputs, batch predictions, and model validation. ```bash cargo run --example advanced_usage ``` -------------------------------- ### Quick Start: Load Model and Predict Source: https://github.com/aryehlev/catboost-rust/blob/publish/README.md Load a trained CatBoost model and make predictions using numeric features. Ensure the model file exists at the specified path. ```rust use catboost_rust::{Model, ObjectsOrderFeatures}; fn main() -> Result<(), Box> { // Load a trained CatBoost model let model = Model::load("path/to/model.cbm")?; // Make predictions with numeric features let features = ObjectsOrderFeatures::new() .with_float_features(&[ &[1.0, 2.0, 3.0, 4.0, 5.0], &[2.0, 3.0, 4.0, 5.0, 6.0], ]); let predictions = model.predict(features)?; println!("Predictions: {:?}", predictions); Ok(()) } ``` -------------------------------- ### Create and Save a CatBoost Regression Model Source: https://github.com/aryehlev/catboost-rust/blob/publish/examples/README.md Trains a CatBoost regression model using sample data and saves it to a binary file. ```python from catboost import CatBoostRegressor import numpy as np # Create sample data X = np.random.rand(100, 5) y = np.sum(X, axis=1) + np.random.normal(0, 0.1, 100) # Train model model = CatBoostRegressor(iterations=100, depth=3, verbose=False) model.fit(X, y) # Save model model.save_model('tmp/my_model.bin') ``` -------------------------------- ### Set CatBoost Version Source: https://github.com/aryehlev/catboost-rust/blob/publish/README.md Specify the CatBoost version to use by setting the CATBOOST_VERSION environment variable before building. The default is '1.2.8'. ```bash export CATBOOST_VERSION=1.2.8 cargo build ``` -------------------------------- ### Build with a specific CatBoost backend version Source: https://context7.com/aryehlev/catboost-rust/llms.txt Set the CATBOOST_VERSION environment variable before running 'cargo build' to specify the CatBoost backend version. ```bash # Pin a specific CatBoost backend version before building export CATBOOST_VERSION=1.2.8 cargo build ``` -------------------------------- ### Enable GPU Support Source: https://github.com/aryehlev/catboost-rust/blob/publish/README.md Compile the crate with the 'gpu' feature to enable GPU acceleration. Then, call `enable_gpu_evaluation()` on the loaded model. ```rust let model = Model::load("model.cbm")?; model.enable_gpu_evaluation()?; ``` -------------------------------- ### Load Model from Buffer (Zero-Copy) Source: https://github.com/aryehlev/catboost-rust/blob/publish/README.md Load a CatBoost model directly from a byte buffer without copying. This is the recommended method for memory efficiency and speed, requiring CatBoost v1.2.9+. ```rust use catboost_rust::Model; use std::fs; let buffer = fs::read("model.cbm")?; let model = Model::load_buffer_zero_copy(buffer)?; ``` -------------------------------- ### Load CatBoost model from file and inspect its properties Source: https://context7.com/aryehlev/catboost-rust/llms.txt Use Model::load to load a CatBoost model from a file path. The resulting Model object is Send + Sync and can be shared across threads. Inspect various model properties like feature counts and tree count. ```rust use catboost_rust::{Model, CatBoostError}; fn main() -> Result<(), CatBoostError> { // Load model from a file path let model = Model::load("path/to/model.cbm")?; // Inspect model shape println!("Float features : {}", model.get_float_features_count()); println!("Cat features : {}", model.get_cat_features_count()); println!("Text features : {}", model.get_text_features_count()); println!("Embedding feats : {}", model.get_embedding_features_count()); println!("Trees : {}", model.get_tree_count()); println!("Dimensions : {}", model.get_dimensions_count()); // Example output: // Float features : 5 // Cat features : 0 // Text features : 0 // Embedding feats : 0 // Trees : 100 // Dimensions : 1 Ok(()) } ``` -------------------------------- ### Load CatBoost model from buffer (zero-copy) Source: https://context7.com/aryehlev/catboost-rust/llms.txt Use Model::load_buffer_zero_copy to load a model from an in-memory buffer without copying. This method is recommended for CatBoost versions 1.2.9 and later and transfers ownership of the buffer to the Model. ```rust use catboost_rust::{Model, CatBoostError}; use std::fs; fn main() -> Result<(), CatBoostError> { // Read model bytes once and pass ownership to Model let buffer: Vec = fs::read("path/to/model.cbm").map_err(|e| CatBoostError { description: format!("IO error: {}", e), })?; // Zero-copy: the buffer is NOT duplicated internally let model = Model::load_buffer_zero_copy(buffer)?; println!("Model loaded. Trees: {}", model.get_tree_count()); // Model loaded. Trees: 100 Ok(()) } ``` -------------------------------- ### Model::load_buffer_zero_copy Source: https://context7.com/aryehlev/catboost-rust/llms.txt Loads a model from an in-memory buffer using a zero-copy approach, recommended for CatBoost versions >= 1.2.9. This method passes the buffer pointer directly to CatBoost without copying, and the buffer is freed automatically on drop. ```APIDOC ## Model::load_buffer_zero_copy — Load a model from an in-memory buffer (zero-copy, recommended) ### Description Available when `CATBOOST_VERSION >= 1.2.9` (the default). Unlike `load_buffer`, this method passes the buffer pointer directly to CatBoost without copying. The `Vec` is moved into the `Model` and freed automatically on drop, eliminating any internal memory pool leaks. ### Method Signature ```rust Model::load_buffer_zero_copy(buffer: Vec) -> CatBoostResult ``` ### Parameters #### Request Body - **buffer** (Vec) - Required - A vector of bytes representing the CatBoost model file. ### Request Example ```rust use catboost_rust::{Model, CatBoostError}; use std::fs; fn main() -> Result<(), CatBoostError> { let buffer: Vec = fs::read("path/to/model.cbm").map_err(|e| CatBoostError { description: format!("IO error: {}", e), })?; let model = Model::load_buffer_zero_copy(buffer)?; // ... use the model ... Ok(()) } ``` ### Response #### Success Response - **Model** - A `Model` object representing the loaded CatBoost model. #### Response Example ```rust println!("Model loaded. Trees: {}", model.get_tree_count()); ``` ``` -------------------------------- ### Model::load Source: https://context7.com/aryehlev/catboost-rust/llms.txt Loads a trained CatBoost model from a .cbm (or .bin) file on disk. Returns a CatBoostResult. The resulting Model is Send + Sync and can be shared safely across threads. ```APIDOC ## Model::load — Load a model from a file path ### Description Loads a trained CatBoost model from a `.cbm` (or `.bin`) file on disk. Returns a `CatBoostResult`. The resulting `Model` is `Send + Sync` and can be shared safely across threads. ### Method Signature ```rust Model::load(path: &str) -> CatBoostResult ``` ### Parameters #### Path Parameters - **path** (string) - Required - The file path to the CatBoost model file (.cbm or .bin). ### Request Example ```rust use catboost_rust::{Model, CatBoostError}; fn main() -> Result<(), CatBoostError> { let model = Model::load("path/to/model.cbm")?; // ... use the model ... Ok(()) } ``` ### Response #### Success Response - **Model** - A `Model` object representing the loaded CatBoost model. #### Response Example ```rust // Example of inspecting model properties after loading println!("Float features : {}", model.get_float_features_count()); println!("Cat features : {}", model.get_cat_features_count()); println!("Text features : {}", model.get_text_features_count()); println!("Embedding feats : {}", model.get_embedding_features_count()); println!("Trees : {}", model.get_tree_count()); println!("Dimensions : {}", model.get_dimensions_count()); ``` ``` -------------------------------- ### Load CatBoost model from buffer (copying) Source: https://context7.com/aryehlev/catboost-rust/llms.txt Use Model::load_buffer to load a model from an in-memory buffer by copying its contents. This is suitable for older CatBoost versions or when buffer ownership cannot be transferred. ```rust use catboost_rust::{Model, CatBoostError}; use std::fs; fn main() -> Result<(), CatBoostError> { let buffer: Vec = fs::read("path/to/model.cbm").map_err(|e| CatBoostError { description: format!("IO error: {}", e), })?; // Buffer is borrowed (copied internally); caller retains ownership let model = Model::load_buffer(&buffer)?; println!("Model loaded (copy). Trees: {}", model.get_tree_count()); Ok(()) } ``` -------------------------------- ### Add catboost-rust to Cargo.toml Source: https://github.com/aryehlev/catboost-rust/blob/publish/README.md Add the catboost-rust dependency to your Cargo.toml file. For GPU support, include the "gpu" feature. ```toml [dependencies] catboost-rust = "0.2.0" ``` ```toml [dependencies] catboost-rust = { version = "0.2.0", features = ["gpu"] } ``` -------------------------------- ### Model::enable_gpu_evaluation Source: https://context7.com/aryehlev/catboost-rust/llms.txt Switches the model's evaluation backend to GPU device 0. This requires the crate to be compiled with the `gpu` feature. It falls back gracefully to CPU if no compatible GPU is present, and errors are non-fatal. ```APIDOC ## Model::enable_gpu_evaluation ### Description Switches the model's evaluation backend to GPU device 0. Requires the crate to be compiled with `features = ["gpu"]`. Falls back gracefully to CPU if no compatible GPU is present; errors are non-fatal. ### Method `enable_gpu_evaluation` ### Parameters None ### Response - `Result<(), Box>`: Ok if successful or GPU is unavailable, Err if an unexpected error occurs. ### Request Example ```rust use catboost_rust::{Model, ObjectsOrderFeatures}; fn main() -> Result<(), Box> { let model = Model::load("path/to/model.cbm")?; // Attempt to enable GPU; log warning on failure rather than panicking match model.enable_gpu_evaluation() { Ok(()) => println!("GPU evaluation enabled."), Err(e) => eprintln!("GPU unavailable, using CPU: {}", e), } // Predictions are now dispatched to GPU if available let preds = model.predict( ObjectsOrderFeatures::new().with_float_features(&[ &[1.0_f32, 2.0, 3.0, 4.0, 5.0], &[6.0, 7.0, 8.0, 9.0, 10.0], ]) )?; println!("GPU preds: {:?}", preds); Ok(()) } ``` ``` -------------------------------- ### Handle CatBoost Errors in Rust Source: https://github.com/aryehlev/catboost-rust/blob/publish/README.md Demonstrates how to load a model and handle potential errors using `CatBoostResult` and `CatBoostError`. Ensure the model file exists and feature data is correctly formatted. ```rust use catboost_rust::{Model, CatBoostError, CatBoostResult}; fn load_and_predict() -> CatBoostResult> { let model = Model::load("model.cbm")?; let features = ObjectsOrderFeatures::new() .with_float_features(&[&[1.0, 2.0, 3.0]]); model.predict(features) } match load_and_predict() { Ok(predictions) => println!("Success: {:?}", predictions), Err(CatBoostError { description }) => println!("Error: {}", description), } ``` -------------------------------- ### Inspect Model Information Source: https://github.com/aryehlev/catboost-rust/blob/publish/README.md Retrieve various properties of a loaded CatBoost model, such as feature counts, tree count, and dimensions. ```rust let model = Model::load("model.cbm")?; println!("Float features: {}", model.get_float_features_count()); println!("Categorical features: {}", model.get_cat_features_count()); println!("Text features: {}", model.get_text_features_count()); println!("Embedding features: {}", model.get_embedding_features_count()); println!("Trees: {}", model.get_tree_count()); println!("Dimensions: {}", model.get_dimensions_count()); ``` -------------------------------- ### Model::load_buffer Source: https://context7.com/aryehlev/catboost-rust/llms.txt Loads a model from an in-memory buffer by copying the provided byte slice into CatBoost's internal memory. Use this when you cannot transfer ownership of the buffer, or when targeting CatBoost versions older than 1.2.9. ```APIDOC ## Model::load_buffer — Load a model from an in-memory buffer (copying) ### Description Loads a model by copying the provided byte slice into CatBoost's internal memory. Use this when you cannot transfer ownership of the buffer, or when targeting CatBoost versions older than 1.2.9. ### Method Signature ```rust Model::load_buffer(buffer: &[u8]) -> CatBoostResult ``` ### Parameters #### Request Body - **buffer** (&[u8]) - Required - A byte slice representing the CatBoost model file. ### Request Example ```rust use catboost_rust::{Model, CatBoostError}; use std::fs; fn main() -> Result<(), CatBoostError> { let buffer: Vec = fs::read("path/to/model.cbm").map_err(|e| CatBoostError { description: format!("IO error: {}", e), })?; let model = Model::load_buffer(&buffer)?; // ... use the model ... Ok(()) } ``` ### Response #### Success Response - **Model** - A `Model` object representing the loaded CatBoost model. #### Response Example ```rust println!("Model loaded (copy). Trees: {}", model.get_tree_count()); ``` ``` -------------------------------- ### Inspect CatBoost Model Features and Names Source: https://context7.com/aryehlev/catboost-rust/llms.txt Load a CatBoost model and retrieve counts for different feature types (float, categorical, text, embedding) and the total tree count. Feature names are available for CatBoost versions 1.2.3 and above, provided the `catboost_feature_indices` flag is enabled. ```rust use catboost_rust::{Model, CatBoostError}; fn main() -> Result<(), CatBoostError> { let model = Model::load("path/to/model.cbm")?; // --- Feature counts (always available) --- println!("float features : {}", model.get_float_features_count()); println!("cat features : {}", model.get_cat_features_count()); println!("text features : {}", model.get_text_features_count()); // CatBoost >= 1.2 println!("embedding features: {}", model.get_embedding_features_count()); // CatBoost >= 1.1.1 println!("tree count : {}", model.get_tree_count()); println!("output dimensions : {}", model.get_dimensions_count()); // --- Feature names (CatBoost >= 1.2.3, cfg flag: catboost_feature_indices) --- #[cfg(catboost_feature_indices)] { let all_names = model.get_feature_names()?; let float_names = model.get_float_feature_names()?; let cat_names = model.get_cat_feature_names()?; let text_names = model.get_text_feature_names()?; let emb_names = model.get_embedding_feature_names()?; println!("all feature names : {:?}", all_names); // all feature names : ["age", "income", "category", "description"] println!("float feature names: {:?}", float_names); // float feature names: ["age", "income"] println!("cat feature names : {:?}", cat_names); // cat feature names : ["category"] println!("text feature names : {:?}", text_names); // text feature names : ["description"] println!("emb feature names : {:?}", emb_names); } Ok(()) } ``` -------------------------------- ### Model Introspection - Feature Counts and Names Source: https://context7.com/aryehlev/catboost-rust/llms.txt This section demonstrates how to use the `Model` struct to retrieve information about the features used by a CatBoost model, including counts and names. Feature names are available for CatBoost versions 1.2.3 and later, provided the `catboost_feature_indices` configuration flag is enabled. ```APIDOC ## Model Introspection — feature counts and names The `Model` struct exposes methods to query the expected feature counts and (with CatBoost ≥ 1.2.3) the names of individual features used by the model. ```rust use catboost_rust::{Model, CatBoostError}; fn main() -> Result<(), CatBoostError> { let model = Model::load("path/to/model.cbm")?; // --- Feature counts (always available) --- println!("float features : {}", model.get_float_features_count()); println!("cat features : {}", model.get_cat_features_count()); println!("text features : {}", model.get_text_features_count()); // CatBoost >= 1.2 println!("embedding features: {}", model.get_embedding_features_count()); // CatBoost >= 1.1.1 println!("tree count : {}", model.get_tree_count()); println!("output dimensions : {}", model.get_dimensions_count()); // --- Feature names (CatBoost >= 1.2.3, cfg flag: catboost_feature_indices) --- #[cfg(catboost_feature_indices)] { let all_names = model.get_feature_names()?; let float_names = model.get_float_feature_names()?; let cat_names = model.get_cat_feature_names()?; let text_names = model.get_text_feature_names()?; let emb_names = model.get_embedding_feature_names()?; println!("all feature names : {:?}", all_names); // all feature names : ["age", "income", "category", "description"] println!("float feature names: {:?}", float_names); // float feature names: ["age", "income"] println!("cat feature names : {:?}", cat_names); // cat feature names : ["category"] println!("text feature names : {:?}", text_names); // text feature names : ["description"] println!("emb feature names : {:?}", emb_names); } Ok(()) } ``` ``` -------------------------------- ### Basic Usage: Numeric Features Prediction Source: https://github.com/aryehlev/catboost-rust/blob/publish/README.md Load a CatBoost model and perform predictions using only numeric features. The model file must be accessible. ```rust use catboost_rust::{Model, ObjectsOrderFeatures}; // Load model from file let model = Model::load("model.cbm")?; // Simple numeric features prediction let features = ObjectsOrderFeatures::new() .with_float_features(&[&[1.0, 2.0, 3.0, 4.0, 5.0]]); let predictions = model.predict(features)?; ``` -------------------------------- ### Build Multi-Modal Feature Sets with ObjectsOrderFeatures Source: https://context7.com/aryehlev/catboost-rust/llms.txt Construct feature sets for CatBoost predictions using the `ObjectsOrderFeatures` builder. This builder enforces compile-time checks for correct feature types. Supports float, categorical, text (requires CatBoost >= 1.1), and embedding features (requires CatBoost >= 1.1.1). ```rust use catboost_rust::{Model, ObjectsOrderFeatures, CatBoostError}; use std::ffi::CString; fn build_features_example(model: &Model) -> Result, CatBoostError> { // Start with an empty container and chain feature setters let features = ObjectsOrderFeatures::new() // Float: outer Vec = samples, inner slice = per-sample float values .with_float_features(&[ &[0.5_f32, 1.0, 2.0], &[1.5, 2.0, 3.0], ]) // Categorical: string slices per sample .with_cat_features(&[ &["urban", "high_income"], &["rural", "low_income"], ]) // Text: CString slices per sample (CatBoost >= 1.1) .with_text_features(&[ &[CString::new("great product").unwrap()], &[CString::new("terrible experience").unwrap()], ]) // Embeddings: Vec> per sample (CatBoost >= 1.1.1) .with_embedding_features(&[ &[vec![0.1, 0.2, 0.3, 0.4]], &[vec![0.9, 0.8, 0.7, 0.6]], ]); model.predict(features) } ``` -------------------------------- ### Enable GPU-accelerated inference in Rust Source: https://context7.com/aryehlev/catboost-rust/llms.txt Use `Model::enable_gpu_evaluation` to switch inference to GPU. Requires the `gpu` feature to be enabled during compilation. The function falls back to CPU if no compatible GPU is found, and errors are non-fatal. ```rust use catboost_rust::{Model, ObjectsOrderFeatures}; fn main() -> Result<(), Box> { let model = Model::load("path/to/model.cbm")?; // Attempt to enable GPU; log warning on failure rather than panicking match model.enable_gpu_evaluation() { Ok(()) => println!("GPU evaluation enabled."), Err(e) => eprintln!("GPU unavailable, using CPU: {}", e), } // Predictions are now dispatched to GPU if available let preds = model.predict( ObjectsOrderFeatures::new().with_float_features(&[ &[1.0_f32, 2.0, 3.0, 4.0, 5.0], &[6.0, 7.0, 8.0, 9.0, 10.0], ]) )?; println!("GPU preds: {:?}", preds); // GPU preds: [0.523141, 0.814762] Ok(()) } ``` -------------------------------- ### CatBoost Error Handling with CatBoostError and CatBoostResult Source: https://context7.com/aryehlev/catboost-rust/llms.txt Handle errors from fallible CatBoost operations using `CatBoostResult`, which is an alias for `Result`. `CatBoostError` implements `std::error::Error` and `Display`, allowing seamless integration with the `?` operator and `Box`. ```rust use catboost_rust::{Model, ObjectsOrderFeatures, CatBoostError, CatBoostResult}; fn run_inference(model_path: &str) -> CatBoostResult> { let model = Model::load(model_path)?; let features = ObjectsOrderFeatures::new() .with_float_features(&[&[1.0_f32, 2.0, 3.0]]); model.predict(features) } fn main() { match run_inference("model.cbm") { Ok(predictions) => println!("Predictions: {:?}", predictions), Err(CatBoostError { description }) => eprintln!("CatBoost error: {}", description), } // Works with Box too let result: Result, Box> = (|| { let model = Model::load("model.cbm")?; Ok(model.predict( ObjectsOrderFeatures::new().with_float_features(&[&[0.5_f32, 1.5]]) )?) })(); if let Err(e) = result { eprintln!("Error (boxed): {}", e); } } ``` -------------------------------- ### CatBoostError and CatBoostResult - Error Handling Source: https://context7.com/aryehlev/catboost-rust/llms.txt This section explains CatBoost's error handling mechanism. All fallible operations return `CatBoostResult`, which is an alias for `Result`. The `CatBoostError` struct implements standard Rust error traits, allowing seamless integration with the `?` operator and `Box`. ```APIDOC ## `CatBoostError` and `CatBoostResult` — error handling All fallible operations return `CatBoostResult` (an alias for `Result`). `CatBoostError` implements `std::error::Error` and `Display`, integrating with the `?` operator and `Box` idioms. ```rust use catboost_rust::{Model, ObjectsOrderFeatures, CatBoostError, CatBoostResult}; fn run_inference(model_path: &str) -> CatBoostResult> { let model = Model::load(model_path)?; let features = ObjectsOrderFeatures::new() .with_float_features(&[&[1.0_f32, 2.0, 3.0]]); model.predict(features) } fn main() { match run_inference("model.cbm") { Ok(predictions) => println!("Predictions: {:?}", predictions), Err(CatBoostError { description }) => eprintln!("CatBoost error: {}", description), } // Works with Box too let result: Result, Box> = (|| { let model = Model::load("model.cbm")?; Ok(model.predict( ObjectsOrderFeatures::new().with_float_features(&[&[0.5_f32, 1.5]]) )?) })(); if let Err(e) = result { eprintln!("Error (boxed): {}", e); } } ``` ``` -------------------------------- ### ObjectsOrderFeatures Builder - Composing Multi-modal Feature Sets Source: https://context7.com/aryehlev/catboost-rust/llms.txt The `ObjectsOrderFeatures` builder is used to construct feature sets for model prediction. It allows chaining methods to add different types of features (float, categorical, text, embedding) in a type-safe manner, ensuring compile-time validation of feature types. ```APIDOC ## `ObjectsOrderFeatures` builder — composing multi-modal feature sets `ObjectsOrderFeatures` is the central feature container. It is constructed with `new()` (all fields default to empty) and each `with_*_features` method returns a new, typed struct — enabling compile-time enforcement that the correct feature types are provided. ```rust use catboost_rust::{Model, ObjectsOrderFeatures, CatBoostError}; use std::ffi::CString; fn build_features_example(model: &Model) -> Result, CatBoostError> { // Start with an empty container and chain feature setters let features = ObjectsOrderFeatures::new() // Float: outer Vec = samples, inner slice = per-sample float values .with_float_features(&[ &[0.5_f32, 1.0, 2.0], &[1.5, 2.0, 3.0], ]) // Categorical: string slices per sample .with_cat_features(&[ &["urban", "high_income"], &["rural", "low_income"], ]) // Text: CString slices per sample (CatBoost >= 1.1) .with_text_features(&[ &[CString::new("great product").unwrap()], &[CString::new("terrible experience").unwrap()], ]) // Embeddings: Vec> per sample (CatBoost >= 1.1.1) .with_embedding_features(&[ &[vec![0.1, 0.2, 0.3, 0.4]], &[vec![0.9, 0.8, 0.7, 0.6]], ]); model.predict(features) } ``` ``` -------------------------------- ### Run inference with ObjectsOrderFeatures in Rust Source: https://context7.com/aryehlev/catboost-rust/llms.txt Use `Model::predict` for flexible inference with float, categorical, text, or embedding features. Accepts `ObjectsOrderFeatures` for complex data structures. Ensure correct feature types and data formats are provided. ```rust use catboost_rust::{Model, ObjectsOrderFeatures, CatBoostError}; use std::ffi::CString; fn main() -> Result<(), CatBoostError> { let model = Model::load("path/to/model.cbm")?; // --- Float features only (3 samples × 5 features) --- let float_preds = model.predict( ObjectsOrderFeatures::new() .with_float_features(&[ &[1.0_f32, 2.0, 3.0, 4.0, 5.0], &[2.0, 3.0, 4.0, 5.0, 6.0], &[3.0, 4.0, 5.0, 6.0, 7.0], ]) )?; println!("Float preds: {:?}", float_preds); // Float preds: [0.523141, 0.631422, 0.718305] // --- Float + categorical features (1 sample) --- let mixed_preds = model.predict( ObjectsOrderFeatures::new() .with_float_features(&[&[1.0_f32, 2.0, 3.0]]) .with_cat_features(&[&["dog", "indoor", "medium"]]) )?; println!("Mixed preds: {:?}", mixed_preds); // Mixed preds: [0.487293] // --- Float + text features (1 sample, requires CatBoost v1.1+) --- let texts = vec![ CString::new("fast gradient boosting").unwrap(), CString::new("rust bindings").unwrap(), ]; let text_preds = model.predict( ObjectsOrderFeatures::new() .with_float_features(&[&[0.5_f32, 1.5]]) .with_text_features(&[&texts]) )?; println!("Text preds: {:?}", text_preds); // --- Float + embedding features (requires CatBoost v1.1.1+) --- let embeddings: Vec> = vec![ vec![0.1, 0.2, 0.3, 0.4], // embedding #1 for sample 0 vec![0.5, 0.6, 0.7, 0.8], // embedding #2 for sample 0 ]; let emb_preds = model.predict( ObjectsOrderFeatures::new() .with_float_features(&[&[1.0_f32, 2.0]]) .with_embedding_features(&[&embeddings]) )?; println!("Embedding preds: {:?}", emb_preds); Ok(()) } ``` -------------------------------- ### Text Features Prediction Source: https://github.com/aryehlev/catboost-rust/blob/publish/README.md Perform predictions with text features. Text data must be converted to CString. Ensure the model is trained to handle text features. ```rust use catboost_rust::{Model, ObjectsOrderFeatures}; use std::ffi::CString; let model = Model::load("model.cbm")?; let text_features = vec![ CString::new("This is a sample text").unwrap(), CString::new("Another text sample").unwrap(), ]; let features = ObjectsOrderFeatures::new() .with_float_features(&[&[1.0, 2.0]]) .with_text_features(&[&text_features]); let predictions = model.predict(features)?; ``` -------------------------------- ### Simplified float + categorical prediction in Rust Source: https://context7.com/aryehlev/catboost-rust/llms.txt Use `Model::calc_model_prediction` as a shortcut for predicting with only float and categorical features. It simplifies `ObjectsOrderFeatures` construction. Ensure correct data types for float and categorical features. ```rust use catboost_rust::{Model, CatBoostError}; fn main() -> Result<(), CatBoostError> { let model = Model::load("path/to/model.cbm")?; // Batch of 3 samples with float features; no categorical features let float_features = vec![ vec![1.0_f32, 2.0, 3.0, 4.0, 5.0], vec![2.0, 3.0, 4.0, 5.0, 6.0], vec![3.0, 4.0, 5.0, 6.0, 7.0], ]; let preds = model.calc_model_prediction( float_features, vec![Vec::::new(); 3], // empty cat features for each sample )?; for (i, p) in preds.iter().enumerate() { println!("Sample {}: {:.6}", i + 1, p); } // Sample 1: 0.523141 // Sample 2: 0.631422 // Sample 3: 0.718305 // With categorical features let num_feats = vec![vec![0.1_f32, 0.2, 0.3]]; let cat_feats = vec![vec!["cat_A".to_string(), "cat_B".to_string()]] ; let pred = model.calc_model_prediction(num_feats, cat_feats)?; println!("With cats: {:.6}", pred[0]); Ok(()) } ``` -------------------------------- ### Categorical Features Prediction Source: https://github.com/aryehlev/catboost-rust/blob/publish/README.md Make predictions using a mix of numeric and categorical features. Ensure the model supports these feature types. ```rust use catboost_rust::{Model, ObjectsOrderFeatures}; let model = Model::load("model.cbm")?; // Mixed numeric and categorical features let features = ObjectsOrderFeatures::new() .with_float_features(&[&[1.0, 2.0, 3.0]]) .with_cat_features(&[&["A", "B", "C"]]); let predictions = model.predict(features)?; ``` -------------------------------- ### Embedding Features Prediction Source: https://github.com/aryehlev/catboost-rust/blob/publish/README.md Make predictions using embedding features. Embeddings should be provided as vectors of floats. The model must be configured for embedding features. ```rust use catboost_rust::{Model, ObjectsOrderFeatures}; let model = Model::load("model.cbm")?; let embeddings = vec![ vec![0.1, 0.2, 0.3, 0.4], // First embedding vec![0.5, 0.6, 0.7, 0.8], // Second embedding ]; let features = ObjectsOrderFeatures::new() .with_float_features(&[&[1.0, 2.0]]) .with_embedding_features(&[&embeddings]); let predictions = model.predict(features)?; ``` -------------------------------- ### Model::predict Source: https://context7.com/aryehlev/catboost-rust/llms.txt Run inference using ObjectsOrderFeatures. This is the primary, fully-generic prediction API that accepts an ObjectsOrderFeatures struct. It can handle float, categorical, text, and embedding features and returns CatBoostResult>. ```APIDOC ## Model::predict ### Description The primary, fully-generic prediction API. Accepts an `ObjectsOrderFeatures` struct that can carry any combination of float, categorical, text, and embedding features via a builder pattern. Returns `CatBoostResult>` where the length equals `object_count × dimensions`. ### Method `predict` ### Parameters - `features`: `ObjectsOrderFeatures` - An object configured with various feature types (float, categorical, text, embedding). ### Response - `CatBoostResult>`: A vector of prediction results, or an error if prediction fails. ### Request Example ```rust use catboost_rust::{Model, ObjectsOrderFeatures, CatBoostError}; use std::ffi::CString; fn main() -> Result<(), CatBoostError> { let model = Model::load("path/to/model.cbm")?; // --- Float features only (3 samples × 5 features) --- let float_preds = model.predict( ObjectsOrderFeatures::new() .with_float_features(&[ &[1.0_f32, 2.0, 3.0, 4.0, 5.0], &[2.0, 3.0, 4.0, 5.0, 6.0], &[3.0, 4.0, 5.0, 6.0, 7.0], ]) )?; println!("Float preds: {:?}", float_preds); // --- Float + categorical features (1 sample) --- let mixed_preds = model.predict( ObjectsOrderFeatures::new() .with_float_features(&[&[1.0_f32, 2.0, 3.0]]) .with_cat_features(&[&["dog", "indoor", "medium"]]) )?; println!("Mixed preds: {:?}", mixed_preds); // --- Float + text features (1 sample, requires CatBoost v1.1+) --- let texts = vec![ CString::new("fast gradient boosting").unwrap(), CString::new("rust bindings").unwrap(), ]; let text_preds = model.predict( ObjectsOrderFeatures::new() .with_float_features(&[&[0.5_f32, 1.5]]) .with_text_features(&[&texts]) )?; println!("Text preds: {:?}", text_preds); // --- Float + embedding features (requires CatBoost v1.1.1+) --- let embeddings: Vec> = vec![ vec![0.1, 0.2, 0.3, 0.4], // embedding #1 for sample 0 vec![0.5, 0.6, 0.7, 0.8], // embedding #2 for sample 0 ]; let emb_preds = model.predict( ObjectsOrderFeatures::new() .with_float_features(&[&[1.0_f32, 2.0]]) .with_embedding_features(&[&embeddings]) )?; println!("Embedding preds: {:?}", emb_preds); Ok(()) } ``` ``` -------------------------------- ### Model::calc_model_prediction Source: https://context7.com/aryehlev/catboost-rust/llms.txt A convenience wrapper around `predict` for the common case of float and categorical features only. It handles the `ObjectsOrderFeatures` construction internally, accepting simple slices. ```APIDOC ## Model::calc_model_prediction ### Description A convenience wrapper around `predict` for the common case of float and categorical features only. Handles the `ObjectsOrderFeatures` construction internally, accepting simple slices. ### Method `calc_model_prediction` ### Parameters - `float_features`: `Vec>` - A vector of samples, where each sample is a vector of float features. - `cat_features`: `Vec>` - A vector of samples, where each sample is a vector of categorical feature strings. ### Response - `CatBoostResult>`: A vector of prediction results, or an error if prediction fails. ### Request Example ```rust use catboost_rust::{Model, CatBoostError}; fn main() -> Result<(), CatBoostError> { let model = Model::load("path/to/model.cbm")?; // Batch of 3 samples with float features; no categorical features let float_features = vec![ vec![1.0_f32, 2.0, 3.0, 4.0, 5.0], vec![2.0, 3.0, 4.0, 5.0, 6.0], vec![3.0, 4.0, 5.0, 6.0, 7.0], ]; let preds = model.calc_model_prediction( float_features, vec![Vec::::new(); 3], // empty cat features for each sample )?; for (i, p) in preds.iter().enumerate() { println!("Sample {}: {:.6}", i + 1, p); } // With categorical features let num_feats = vec![vec![0.1_f32, 0.2, 0.3]]; let cat_feats = vec![vec!["cat_A".to_string(), "cat_B".to_string()]] ; let pred = model.calc_model_prediction(num_feats, cat_feats)?; println!("With cats: {:.6}", pred[0]); Ok(()) } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.