Models
This document provides comprehensive documentation for model-related classes in the ViewAI Python SDK.
Overview
The ViewAI SDK provides several model-related classes:
Model: Deploy and manage trained ML models
Prediction: Encapsulate prediction results
DataPoint: Validate individual data points for prediction
ModelSchemaManager: Manage model schemas and validation
Model
The Model class handles the complete lifecycle of machine learning model deployment to the ViewAI platform.
Key Features
Automatic ONNX export from sklearn models for version-agnostic deployment
Comprehensive schema generation and validation
Model deployment to ViewAI backend with S3 upload
Schema management with type validation and category constraints
Backward compatibility with pickle-based deployment
Initialization
Parameters:
model(Any): Trained sklearn model or pipeline (must be compatible with sklearn's API)df(DataFrame): Training dataframe used for schema generation (should contain all feature columns and target)target(str): Name of the target column in the dataframeschema(dict or ModelSchemaManager, optional): Model schema specificationNone: Auto-generate schema from model and datadict: Pre-defined schema dictionaryModelSchemaManager: Existing schema manager instance
name(str): Human-readable name for the model deploymentworkspace(Workspace): Workspace object with workspace_id attributeproject(Project, optional): Optional Project object with project_id attributeclient(ViewAIClient): ViewAIClient instance for API communicationexport_format(str): Export format for the model (default: "onnx")"onnx"(recommended): Cross-platform, version-agnostic format"pickle"(legacy): Python-specific serialization
Example:
deploy()
deploy()Deploy pre-trained model to ViewAI platform.
Returns: Dashboard ID (str) for the deployed model, or None if deployment fails
Example:
Process:
Schema Management Methods
get_schema()
get_schema()Get the current model schema.
Returns: Complete schema dictionary with all field specifications
Example:
update_schema_column_categories(column_name, categories=None, allow_new_categories=None)
update_schema_column_categories(column_name, categories=None, allow_new_categories=None)Update categories for a categorical column in the schema.
Parameters:
column_name(str): Name of the categorical column to updatecategories(List, optional): New list of allowed category valuesallow_new_categories(bool, optional): Whether to allow new categories at inference time
Returns: self (for method chaining)
Example:
update_schema_column_range(column_name, min_value=None, max_value=None)
update_schema_column_range(column_name, min_value=None, max_value=None)Update value range for a numerical column in the schema.
Parameters:
column_name(str): Name of the numerical column to updatemin_value(float, optional): Minimum allowed value (inclusive)max_value(float, optional): Maximum allowed value (inclusive)
Returns: self (for method chaining)
Example:
update_schema_column_type(column_name, data_type)
update_schema_column_type(column_name, data_type)Update data type for a column in the schema.
Parameters:
column_name(str): Name of the column to updatedata_type(str): New data type. Must be one of:"int": Integer values"float": Floating point values"category": Categorical/discrete values"str": String values
Returns: self (for method chaining)
Example:
save_schema_locally(file_path="schema.json")
save_schema_locally(file_path="schema.json")Save schema to a local JSON file.
Parameters:
file_path(str): Path where schema JSON will be saved (default: "schema.json")
Returns: self (for method chaining)
Example:
preview_schema()
preview_schema()Print a formatted preview of the schema.
Returns: self (for method chaining)
Example:
Output:
validate_data(df)
validate_data(df)Validate a dataframe against the current schema.
Parameters:
df(DataFrame): DataFrame to validate against the schema
Returns: Dictionary containing validation results:
'valid'(bool): True if validation passed'errors'(list): List of error messages
Example:
Complete Model Example
Prediction
The Prediction class encapsulates prediction results and provides methods to extract specific information.
Initialization
Parameters:
data(dict): Dictionary containing prediction results and associated data
Example:
get_probabilities()
get_probabilities()Extract probability values or predicted categories from the prediction.
Returns: Dictionary containing relevant probability or prediction data
Example:
get_timestamp()
get_timestamp()Retrieve the timestamp associated with the prediction.
Returns: Timestamp string or empty string if not available
Example:
get_raw_prediction()
get_raw_prediction()Return the complete raw prediction data.
Returns: The complete prediction data dictionary
Example:
get(key, default=None)
get(key, default=None)Get a specific value from the prediction data.
Parameters:
key(str): The key to retrieve from prediction datadefault(Any): Default value to return if key is not found
Returns: Value associated with the key, or default if not found
Example:
Dictionary-like Access
The Prediction class supports dictionary-style access:
Example:
DataPoint
The DataPoint class validates individual data points against model schemas before sending them for prediction.
Initialization
Parameters:
data(dict): The data point structured as a dictionarymodel_id(str): The identifier for the model to score againstapi_key(str): API key used to authenticate and retrieve the model schema
Example:
get_data()
get_data()Validate and return the data point.
Returns: The validated data dictionary
Raises:
ValueError: If validation fails
Example:
validate_data()
validate_data()Validate the data point against the schema's validation rules.
Raises:
ValueError: If any validation rule is violated
Example:
ModelSchemaManager
The ModelSchemaManager class manages loading and applying model-specific schemas for validation and configuration.
Initialization
Parameters:
model_id(str, optional): Unique identifier for the modelapi_key(str, optional): API key for backend service authentication
Example:
Schema Loading and Saving
fetch_schema_from_api(model_id)
fetch_schema_from_api(model_id)Fetch a schema from the backend service via an API call.
Parameters:
model_id(str): Model ID for which the schema needs to be fetched
Returns: Loaded schema dictionary or empty dictionary if request fails
Example:
upload_schema_to_api(model_id, schema)
upload_schema_to_api(model_id, schema)Upload a schema to the backend service via an API call.
Parameters:
model_id(str): Model ID for which the schema should be uploadedschema(dict): Schema dictionary to be uploaded
Returns: Response dictionary from API or empty dictionary if request fails
Example:
load_schema_from_file(file_path)
load_schema_from_file(file_path)Load a schema from a JSON file.
Parameters:
file_path(str): Path to the JSON file containing the schema
Returns: Loaded schema dictionary or empty dictionary if file cannot be read
Example:
save_schema_to_file(file_path)
save_schema_to_file(file_path)Save the current schema to a JSON file.
Parameters:
file_path(str): Path to the JSON file where the schema should be saved
Example:
Schema Generation
generate_schema_from_dataframe(model, df, allowed_categories=None, always_allow_categories=False)
generate_schema_from_dataframe(model, df, allowed_categories=None, always_allow_categories=False)Generate a comprehensive schema based on model features and DataFrame.
Parameters:
model(Any): The machine learning model or pipelinedf(DataFrame): The DataFrame used for training the modelallowed_categories(List[str], optional): List of features where new categories are allowedalways_allow_categories(bool): If True, allow new categories in all categorical features
Returns: Generated model schema with comprehensive field definitions
Example:
Schema Modification
update_column_categories(column_name, categories=None, allow_new_categories=None)
update_column_categories(column_name, categories=None, allow_new_categories=None)Update the possible values and handling of new categories for a categorical column.
Parameters:
column_name(str): The name of the column to updatecategories(List, optional): A list of new categoriesallow_new_categories(bool, optional): Whether to allow new categories
Example:
update_column_range(column_name, min_value, max_value)
update_column_range(column_name, min_value, max_value)Update the value range for a specific numeric column.
Parameters:
column_name(str): The name of the column to updatemin_value(int or float): The new minimum allowed valuemax_value(int or float): The new maximum allowed value
Example:
update_column_data_type(column_name, data_type)
update_column_data_type(column_name, data_type)Update the data type of a column in the schema.
Parameters:
column_name(str): The name of the column to updatedata_type(str): The new data type ('int', 'float', 'str', 'category')
Example:
Validation
get_validation_rules()
get_validation_rules()Extract validation rules from the loaded schema.
Returns: Dictionary of validation rules with validator functions and error messages
Example:
handle_missing_values(df, missing_value_rules=None)
handle_missing_values(df, missing_value_rules=None)Handle missing values in the DataFrame according to custom or default rules.
Parameters:
df(DataFrame): The DataFrame to processmissing_value_rules(dict, optional): Dictionary specifying how to handle missing values
Returns: DataFrame with missing values handled
Example:
Complete Schema Example
See Also
ViewAIClient - Main client class
Service Classes - Detailed service class documentation
Configuration - Configuration options
Exceptions - Exception handling
Was this helpful?